blob: da7619d0f466dd6a9de01efb5f1846da8ae740a4 [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"
Douglas Gregord1702062010-04-29 00:18:15 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000023#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000024#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000026#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000027#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000029#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000030#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000031#include "clang/Lex/LiteralSupport.h"
32#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000033#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Designator.h"
35#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000036#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000037#include "clang/Sema/ParsedTemplate.h"
John McCallde6836a2010-08-24 07:21:54 +000038#include "clang/Sema/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000039using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000040using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000041
David Chisnall9f57c292009-08-17 16:35:33 +000042
Douglas Gregor171c45a2009-02-18 21:56:37 +000043/// \brief Determine whether the use of this declaration is valid, and
44/// emit any corresponding diagnostics.
45///
46/// This routine diagnoses various problems with referencing
47/// declarations that can occur when using a declaration. For example,
48/// it might warn if a deprecated or unavailable declaration is being
49/// used, or produce an error (and return true) if a C++0x deleted
50/// function is being used.
51///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000052/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattnerb7df3c62009-10-25 22:31:57 +000053/// decls.
54///
Douglas Gregor171c45a2009-02-18 21:56:37 +000055/// \returns true if there was an error (this declaration cannot be
56/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000057///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000058bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahaniandbbdd2f2011-04-23 17:27:19 +000059 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000060 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
61 // If there were any diagnostics suppressed by template argument deduction,
62 // emit them now.
63 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
64 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
65 if (Pos != SuppressedDiagnostics.end()) {
66 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
67 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
68 Diag(Suppressed[I].first, Suppressed[I].second);
69
70 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000071 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000072 // entry from the table, because we want to avoid ever emitting these
73 // diagnostics again.
74 Suppressed.clear();
75 }
76 }
77
Richard Smith30482bc2011-02-20 03:19:35 +000078 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +000079 if (ParsingInitForAutoVars.count(D)) {
80 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
81 << D->getDeclName();
82 return true;
Richard Smith30482bc2011-02-20 03:19:35 +000083 }
84
Douglas Gregor171c45a2009-02-18 21:56:37 +000085 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000086 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000087 if (FD->isDeleted()) {
88 Diag(Loc, diag::err_deleted_function_use);
89 Diag(D->getLocation(), diag::note_unavailable_here) << true;
90 return true;
91 }
Douglas Gregorde681d42009-02-24 04:26:15 +000092 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000093
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000094 // See if this declaration is unavailable or deprecated.
95 std::string Message;
96 switch (D->getAvailability(&Message)) {
97 case AR_Available:
98 case AR_NotYetIntroduced:
99 break;
100
101 case AR_Deprecated:
102 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
103 break;
104
105 case AR_Unavailable:
106 if (Message.empty()) {
107 if (!UnknownObjCClass)
108 Diag(Loc, diag::err_unavailable) << D->getDeclName();
109 else
110 Diag(Loc, diag::warn_unavailable_fwdclass_message)
111 << D->getDeclName();
112 }
113 else
114 Diag(Loc, diag::err_unavailable_message)
115 << D->getDeclName() << Message;
116 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
117 break;
118 }
119
Anders Carlsson73067a02010-10-22 23:37:08 +0000120 // Warn if this is used but marked unused.
121 if (D->hasAttr<UnusedAttr>())
122 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
123
Douglas Gregor171c45a2009-02-18 21:56:37 +0000124 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000125}
126
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000127/// \brief Retrieve the message suffix that should be added to a
128/// diagnostic complaining about the given function being deleted or
129/// unavailable.
130std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
131 // FIXME: C++0x implicitly-deleted special member functions could be
132 // detected here so that we could improve diagnostics to say, e.g.,
133 // "base class 'A' had a deleted copy constructor".
134 if (FD->isDeleted())
135 return std::string();
136
137 std::string Message;
138 if (FD->getAvailability(&Message))
139 return ": " + Message;
140
141 return std::string();
142}
143
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000144/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +0000145/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000146/// attribute. It warns if call does not have the sentinel argument.
147///
148void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000149 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000150 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000151 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000152 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000153
154 // FIXME: In C++0x, if any of the arguments are parameter pack
155 // expansions, we can't check for the sentinel now.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000156 int sentinelPos = attr->getSentinel();
157 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000158
Mike Stump87c57ac2009-05-16 07:39:55 +0000159 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
160 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000161 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000162 bool warnNotEnoughArgs = false;
163 int isMethod = 0;
164 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
165 // skip over named parameters.
166 ObjCMethodDecl::param_iterator P, E = MD->param_end();
167 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
168 if (nullPos)
169 --nullPos;
170 else
171 ++i;
172 }
173 warnNotEnoughArgs = (P != E || i >= NumArgs);
174 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000175 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000176 // skip over named parameters.
177 ObjCMethodDecl::param_iterator P, E = FD->param_end();
178 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
179 if (nullPos)
180 --nullPos;
181 else
182 ++i;
183 }
184 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000185 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000186 // block or function pointer call.
187 QualType Ty = V->getType();
188 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000189 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000190 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
191 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000192 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
193 unsigned NumArgsInProto = Proto->getNumArgs();
194 unsigned k;
195 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
196 if (nullPos)
197 --nullPos;
198 else
199 ++i;
200 }
201 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
202 }
203 if (Ty->isBlockPointerType())
204 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000205 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000206 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000207 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000208 return;
209
210 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000211 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000212 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000213 return;
214 }
215 int sentinel = i;
216 while (sentinelPos > 0 && i < NumArgs-1) {
217 --sentinelPos;
218 ++i;
219 }
220 if (sentinelPos > 0) {
221 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000222 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000223 return;
224 }
225 while (i < NumArgs-1) {
226 ++i;
227 ++sentinel;
228 }
229 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000230 if (!sentinelExpr) return;
231 if (sentinelExpr->isTypeDependent()) return;
232 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000233
234 // nullptr_t is always treated as null.
235 if (sentinelExpr->getType()->isNullPtrType()) return;
236
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000237 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000238 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
239 Expr::NPC_ValueDependentIsNull))
240 return;
241
242 // Unfortunately, __null has type 'int'.
243 if (isa<GNUNullExpr>(sentinelExpr)) return;
244
245 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
246 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000247}
248
Douglas Gregor87f95b02009-02-26 21:00:50 +0000249SourceRange Sema::getExprRange(ExprTy *E) const {
250 Expr *Ex = (Expr *)E;
251 return Ex? Ex->getSourceRange() : SourceRange();
252}
253
Chris Lattner513165e2008-07-25 21:10:04 +0000254//===----------------------------------------------------------------------===//
255// Standard Promotions and Conversions
256//===----------------------------------------------------------------------===//
257
Chris Lattner513165e2008-07-25 21:10:04 +0000258/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000259ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattner513165e2008-07-25 21:10:04 +0000260 QualType Ty = E->getType();
261 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
262
Chris Lattner513165e2008-07-25 21:10:04 +0000263 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000264 E = ImpCastExprToType(E, Context.getPointerType(Ty),
265 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000266 else if (Ty->isArrayType()) {
267 // In C90 mode, arrays only promote to pointers if the array expression is
268 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
269 // type 'array of type' is converted to an expression that has type 'pointer
270 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
271 // that has type 'array of type' ...". The relevant change is "an lvalue"
272 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000273 //
274 // C++ 4.2p1:
275 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
276 // T" can be converted to an rvalue of type "pointer to T".
277 //
John McCall086a4642010-11-24 05:12:34 +0000278 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000279 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
280 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000281 }
John Wiegley01296292011-04-08 18:41:53 +0000282 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000283}
284
John Wiegley01296292011-04-08 18:41:53 +0000285ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000286 // C++ [conv.lval]p1:
287 // A glvalue of a non-function, non-array type T can be
288 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000289 if (!E->isGLValue()) return Owned(E);
John McCall34376a62010-12-04 03:47:34 +0000290
John McCall27584242010-12-06 20:48:59 +0000291 QualType T = E->getType();
292 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000293
John McCall27584242010-12-06 20:48:59 +0000294 // Create a load out of an ObjCProperty l-value, if necessary.
295 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000296 ExprResult Res = ConvertPropertyForRValue(E);
297 if (Res.isInvalid())
298 return Owned(E);
299 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000300 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000301 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000302 }
John McCall27584242010-12-06 20:48:59 +0000303
304 // We don't want to throw lvalue-to-rvalue casts on top of
305 // expressions of certain types in C++.
306 if (getLangOptions().CPlusPlus &&
307 (E->getType() == Context.OverloadTy ||
308 T->isDependentType() ||
309 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000310 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000311
312 // The C standard is actually really unclear on this point, and
313 // DR106 tells us what the result should be but not why. It's
314 // generally best to say that void types just doesn't undergo
315 // lvalue-to-rvalue at all. Note that expressions of unqualified
316 // 'void' type are never l-values, but qualified void can be.
317 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000318 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000319
320 // C++ [conv.lval]p1:
321 // [...] If T is a non-class type, the type of the prvalue is the
322 // cv-unqualified version of T. Otherwise, the type of the
323 // rvalue is T.
324 //
325 // C99 6.3.2.1p2:
326 // If the lvalue has qualified type, the value has the unqualified
327 // version of the type of the lvalue; otherwise, the value has the
328 // type of the lvalue.
329 if (T.hasQualifiers())
330 T = T.getUnqualifiedType();
331
Ted Kremenekdf26df72011-03-01 18:41:00 +0000332 CheckArrayAccess(E);
Ted Kremenek64699be2011-02-16 01:57:07 +0000333
John Wiegley01296292011-04-08 18:41:53 +0000334 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
335 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000336}
337
John Wiegley01296292011-04-08 18:41:53 +0000338ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
339 ExprResult Res = DefaultFunctionArrayConversion(E);
340 if (Res.isInvalid())
341 return ExprError();
342 Res = DefaultLvalueConversion(Res.take());
343 if (Res.isInvalid())
344 return ExprError();
345 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000346}
347
348
Chris Lattner513165e2008-07-25 21:10:04 +0000349/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000350/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000351/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000352/// apply if the array is an argument to the sizeof or address (&) operators.
353/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000354ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000355 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000356 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
357 if (Res.isInvalid())
358 return Owned(E);
359 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000360
361 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000362 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000363
364 // Try to perform integral promotions if the object has a theoretically
365 // promotable type.
366 if (Ty->isIntegralOrUnscopedEnumerationType()) {
367 // C99 6.3.1.1p2:
368 //
369 // The following may be used in an expression wherever an int or
370 // unsigned int may be used:
371 // - an object or expression with an integer type whose integer
372 // conversion rank is less than or equal to the rank of int
373 // and unsigned int.
374 // - A bit-field of type _Bool, int, signed int, or unsigned int.
375 //
376 // If an int can represent all values of the original type, the
377 // value is converted to an int; otherwise, it is converted to an
378 // unsigned int. These are called the integer promotions. All
379 // other types are unchanged by the integer promotions.
380
381 QualType PTy = Context.isPromotableBitField(E);
382 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000383 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
384 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000385 }
386 if (Ty->isPromotableIntegerType()) {
387 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000388 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
389 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000390 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000391 }
John Wiegley01296292011-04-08 18:41:53 +0000392 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000393}
394
Chris Lattner2ce500f2008-07-25 22:25:12 +0000395/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000396/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000397/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000398ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
399 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000400 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000401
John Wiegley01296292011-04-08 18:41:53 +0000402 ExprResult Res = UsualUnaryConversions(E);
403 if (Res.isInvalid())
404 return Owned(E);
405 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000406
Chris Lattner2ce500f2008-07-25 22:25:12 +0000407 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000408 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000409 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
410
411 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000412}
413
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000414/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
415/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000416/// interfaces passed by value.
417ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000418 FunctionDecl *FDecl) {
John Wiegley01296292011-04-08 18:41:53 +0000419 ExprResult ExprRes = DefaultArgumentPromotion(E);
420 if (ExprRes.isInvalid())
421 return ExprError();
422 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000423
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000424 // __builtin_va_start takes the second argument as a "varargs" argument, but
425 // it doesn't actually do anything with it. It doesn't need to be non-pod
426 // etc.
427 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley01296292011-04-08 18:41:53 +0000428 return Owned(E);
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000429
John Wiegley01296292011-04-08 18:41:53 +0000430 if (E->getType()->isObjCObjectType() &&
431 DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000432 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
John Wiegley01296292011-04-08 18:41:53 +0000433 << E->getType() << CT))
434 return ExprError();
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000435
John Wiegley01296292011-04-08 18:41:53 +0000436 if (!E->getType()->isPODType() &&
437 DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000438 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
John Wiegley01296292011-04-08 18:41:53 +0000439 << E->getType() << CT))
440 return ExprError();
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000441
John Wiegley01296292011-04-08 18:41:53 +0000442 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000443}
444
Chris Lattner513165e2008-07-25 21:10:04 +0000445/// UsualArithmeticConversions - Performs various conversions that are common to
446/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000447/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000448/// responsible for emitting appropriate error diagnostics.
449/// FIXME: verify the conversion rules for "complex int" are consistent with
450/// GCC.
John Wiegley01296292011-04-08 18:41:53 +0000451QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
Chris Lattner513165e2008-07-25 21:10:04 +0000452 bool isCompAssign) {
John Wiegley01296292011-04-08 18:41:53 +0000453 if (!isCompAssign) {
454 lhsExpr = UsualUnaryConversions(lhsExpr.take());
455 if (lhsExpr.isInvalid())
456 return QualType();
457 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000458
John Wiegley01296292011-04-08 18:41:53 +0000459 rhsExpr = UsualUnaryConversions(rhsExpr.take());
460 if (rhsExpr.isInvalid())
461 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000462
Mike Stump11289f42009-09-09 15:08:12 +0000463 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000464 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000465 QualType lhs =
John Wiegley01296292011-04-08 18:41:53 +0000466 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000467 QualType rhs =
John Wiegley01296292011-04-08 18:41:53 +0000468 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000469
470 // If both types are identical, no conversion is needed.
471 if (lhs == rhs)
472 return lhs;
473
474 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
475 // The caller can deal with this (e.g. pointer + int).
476 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
477 return lhs;
478
John McCalld005ac92010-11-13 08:17:45 +0000479 // Apply unary and bitfield promotions to the LHS's type.
480 QualType lhs_unpromoted = lhs;
481 if (lhs->isPromotableIntegerType())
482 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley01296292011-04-08 18:41:53 +0000483 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000484 if (!LHSBitfieldPromoteTy.isNull())
485 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000486 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000487 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000488
John McCalld005ac92010-11-13 08:17:45 +0000489 // If both types are identical, no conversion is needed.
490 if (lhs == rhs)
491 return lhs;
492
493 // At this point, we have two different arithmetic types.
494
495 // Handle complex types first (C99 6.3.1.8p1).
496 bool LHSComplexFloat = lhs->isComplexType();
497 bool RHSComplexFloat = rhs->isComplexType();
498 if (LHSComplexFloat || RHSComplexFloat) {
499 // if we have an integer operand, the result is the complex type.
500
John McCallc5e62b42010-11-13 09:02:35 +0000501 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
502 if (rhs->isIntegerType()) {
503 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000504 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
505 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000506 } else {
507 assert(rhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000508 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000509 }
John McCalld005ac92010-11-13 08:17:45 +0000510 return lhs;
511 }
512
John McCallc5e62b42010-11-13 09:02:35 +0000513 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
514 if (!isCompAssign) {
515 // int -> float -> _Complex float
516 if (lhs->isIntegerType()) {
517 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000518 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
519 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000520 } else {
521 assert(lhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000522 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000523 }
524 }
John McCalld005ac92010-11-13 08:17:45 +0000525 return rhs;
526 }
527
528 // This handles complex/complex, complex/float, or float/complex.
529 // When both operands are complex, the shorter operand is converted to the
530 // type of the longer, and that is the type of the result. This corresponds
531 // to what is done when combining two real floating-point operands.
532 // The fun begins when size promotion occur across type domains.
533 // From H&S 6.3.4: When one operand is complex and the other is a real
534 // floating-point type, the less precise type is converted, within it's
535 // real or complex domain, to the precision of the other type. For example,
536 // when combining a "long double" with a "double _Complex", the
537 // "double _Complex" is promoted to "long double _Complex".
538 int order = Context.getFloatingTypeOrder(lhs, rhs);
539
540 // If both are complex, just cast to the more precise type.
541 if (LHSComplexFloat && RHSComplexFloat) {
542 if (order > 0) {
543 // _Complex float -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000544 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000545 return lhs;
546
547 } else if (order < 0) {
548 // _Complex float -> _Complex double
549 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000550 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000551 return rhs;
552 }
553 return lhs;
554 }
555
556 // If just the LHS is complex, the RHS needs to be converted,
557 // and the LHS might need to be promoted.
558 if (LHSComplexFloat) {
559 if (order > 0) { // LHS is wider
560 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000561 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000562 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
563 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000564 return lhs;
565 }
566
567 // RHS is at least as wide. Find its corresponding complex type.
568 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
569
570 // double -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000571 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000572
573 // _Complex float -> _Complex double
574 if (!isCompAssign && order < 0)
John Wiegley01296292011-04-08 18:41:53 +0000575 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000576
577 return result;
578 }
579
580 // Just the RHS is complex, so the LHS needs to be converted
581 // and the RHS might need to be promoted.
582 assert(RHSComplexFloat);
583
584 if (order < 0) { // RHS is wider
585 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000586 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000587 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000588 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
589 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000590 }
John McCalld005ac92010-11-13 08:17:45 +0000591 return rhs;
592 }
593
594 // LHS is at least as wide. Find its corresponding complex type.
595 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
596
597 // double -> _Complex double
598 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000599 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000600
601 // _Complex float -> _Complex double
602 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +0000603 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000604
605 return result;
606 }
607
608 // Now handle "real" floating types (i.e. float, double, long double).
609 bool LHSFloat = lhs->isRealFloatingType();
610 bool RHSFloat = rhs->isRealFloatingType();
611 if (LHSFloat || RHSFloat) {
612 // If we have two real floating types, convert the smaller operand
613 // to the bigger result.
614 if (LHSFloat && RHSFloat) {
615 int order = Context.getFloatingTypeOrder(lhs, rhs);
616 if (order > 0) {
John Wiegley01296292011-04-08 18:41:53 +0000617 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000618 return lhs;
619 }
620
621 assert(order < 0 && "illegal float comparison");
622 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000623 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000624 return rhs;
625 }
626
627 // If we have an integer operand, the result is the real floating type.
628 if (LHSFloat) {
629 if (rhs->isIntegerType()) {
630 // Convert rhs to the lhs floating point type.
John Wiegley01296292011-04-08 18:41:53 +0000631 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000632 return lhs;
633 }
634
635 // Convert both sides to the appropriate complex float.
636 assert(rhs->isComplexIntegerType());
637 QualType result = Context.getComplexType(lhs);
638
639 // _Complex int -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000640 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000641
642 // float -> _Complex float
643 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000644 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000645
646 return result;
647 }
648
649 assert(RHSFloat);
650 if (lhs->isIntegerType()) {
651 // Convert lhs to the rhs floating point type.
652 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000653 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000654 return rhs;
655 }
656
657 // Convert both sides to the appropriate complex float.
658 assert(lhs->isComplexIntegerType());
659 QualType result = Context.getComplexType(rhs);
660
661 // _Complex int -> _Complex float
662 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000663 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000664
665 // float -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000666 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000667
668 return result;
669 }
670
671 // Handle GCC complex int extension.
672 // FIXME: if the operands are (int, _Complex long), we currently
673 // don't promote the complex. Also, signedness?
674 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
675 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
676 if (lhsComplexInt && rhsComplexInt) {
677 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
678 rhsComplexInt->getElementType());
679 assert(order && "inequal types with equal element ordering");
680 if (order > 0) {
681 // _Complex int -> _Complex long
John Wiegley01296292011-04-08 18:41:53 +0000682 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000683 return lhs;
684 }
685
686 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000687 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000688 return rhs;
689 } else if (lhsComplexInt) {
690 // int -> _Complex int
John Wiegley01296292011-04-08 18:41:53 +0000691 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000692 return lhs;
693 } else if (rhsComplexInt) {
694 // int -> _Complex int
695 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000696 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000697 return rhs;
698 }
699
700 // Finally, we have two differing integer types.
701 // The rules for this case are in C99 6.3.1.8
702 int compare = Context.getIntegerTypeOrder(lhs, rhs);
703 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
704 rhsSigned = rhs->hasSignedIntegerRepresentation();
705 if (lhsSigned == rhsSigned) {
706 // Same signedness; use the higher-ranked type
707 if (compare >= 0) {
John Wiegley01296292011-04-08 18:41:53 +0000708 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000709 return lhs;
710 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000711 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000712 return rhs;
713 } else if (compare != (lhsSigned ? 1 : -1)) {
714 // The unsigned type has greater than or equal rank to the
715 // signed type, so use the unsigned type
716 if (rhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000717 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000718 return lhs;
719 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000720 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000721 return rhs;
722 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
723 // The two types are different widths; if we are here, that
724 // means the signed type is larger than the unsigned type, so
725 // use the signed type.
726 if (lhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000727 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000728 return lhs;
729 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000730 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000731 return rhs;
732 } else {
733 // The signed type is higher-ranked than the unsigned type,
734 // but isn't actually any bigger (like unsigned int and long
735 // on most 32-bit systems). Use the unsigned type corresponding
736 // to the signed type.
737 QualType result =
738 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley01296292011-04-08 18:41:53 +0000739 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000740 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000741 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000742 return result;
743 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000744}
745
Chris Lattner513165e2008-07-25 21:10:04 +0000746//===----------------------------------------------------------------------===//
747// Semantic Analysis for various Expression Types
748//===----------------------------------------------------------------------===//
749
750
Peter Collingbourne91147592011-04-15 00:35:48 +0000751ExprResult
752Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
753 SourceLocation DefaultLoc,
754 SourceLocation RParenLoc,
755 Expr *ControllingExpr,
756 MultiTypeArg types,
757 MultiExprArg exprs) {
758 unsigned NumAssocs = types.size();
759 assert(NumAssocs == exprs.size());
760
761 ParsedType *ParsedTypes = types.release();
762 Expr **Exprs = exprs.release();
763
764 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
765 for (unsigned i = 0; i < NumAssocs; ++i) {
766 if (ParsedTypes[i])
767 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
768 else
769 Types[i] = 0;
770 }
771
772 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
773 ControllingExpr, Types, Exprs,
774 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000775 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000776 return ER;
777}
778
779ExprResult
780Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
781 SourceLocation DefaultLoc,
782 SourceLocation RParenLoc,
783 Expr *ControllingExpr,
784 TypeSourceInfo **Types,
785 Expr **Exprs,
786 unsigned NumAssocs) {
787 bool TypeErrorFound = false,
788 IsResultDependent = ControllingExpr->isTypeDependent(),
789 ContainsUnexpandedParameterPack
790 = ControllingExpr->containsUnexpandedParameterPack();
791
792 for (unsigned i = 0; i < NumAssocs; ++i) {
793 if (Exprs[i]->containsUnexpandedParameterPack())
794 ContainsUnexpandedParameterPack = true;
795
796 if (Types[i]) {
797 if (Types[i]->getType()->containsUnexpandedParameterPack())
798 ContainsUnexpandedParameterPack = true;
799
800 if (Types[i]->getType()->isDependentType()) {
801 IsResultDependent = true;
802 } else {
803 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
804 // complete object type other than a variably modified type."
805 unsigned D = 0;
806 if (Types[i]->getType()->isIncompleteType())
807 D = diag::err_assoc_type_incomplete;
808 else if (!Types[i]->getType()->isObjectType())
809 D = diag::err_assoc_type_nonobject;
810 else if (Types[i]->getType()->isVariablyModifiedType())
811 D = diag::err_assoc_type_variably_modified;
812
813 if (D != 0) {
814 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
815 << Types[i]->getTypeLoc().getSourceRange()
816 << Types[i]->getType();
817 TypeErrorFound = true;
818 }
819
820 // C1X 6.5.1.1p2 "No two generic associations in the same generic
821 // selection shall specify compatible types."
822 for (unsigned j = i+1; j < NumAssocs; ++j)
823 if (Types[j] && !Types[j]->getType()->isDependentType() &&
824 Context.typesAreCompatible(Types[i]->getType(),
825 Types[j]->getType())) {
826 Diag(Types[j]->getTypeLoc().getBeginLoc(),
827 diag::err_assoc_compatible_types)
828 << Types[j]->getTypeLoc().getSourceRange()
829 << Types[j]->getType()
830 << Types[i]->getType();
831 Diag(Types[i]->getTypeLoc().getBeginLoc(),
832 diag::note_compat_assoc)
833 << Types[i]->getTypeLoc().getSourceRange()
834 << Types[i]->getType();
835 TypeErrorFound = true;
836 }
837 }
838 }
839 }
840 if (TypeErrorFound)
841 return ExprError();
842
843 // If we determined that the generic selection is result-dependent, don't
844 // try to compute the result expression.
845 if (IsResultDependent)
846 return Owned(new (Context) GenericSelectionExpr(
847 Context, KeyLoc, ControllingExpr,
848 Types, Exprs, NumAssocs, DefaultLoc,
849 RParenLoc, ContainsUnexpandedParameterPack));
850
851 llvm::SmallVector<unsigned, 1> CompatIndices;
852 unsigned DefaultIndex = -1U;
853 for (unsigned i = 0; i < NumAssocs; ++i) {
854 if (!Types[i])
855 DefaultIndex = i;
856 else if (Context.typesAreCompatible(ControllingExpr->getType(),
857 Types[i]->getType()))
858 CompatIndices.push_back(i);
859 }
860
861 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
862 // type compatible with at most one of the types named in its generic
863 // association list."
864 if (CompatIndices.size() > 1) {
865 // We strip parens here because the controlling expression is typically
866 // parenthesized in macro definitions.
867 ControllingExpr = ControllingExpr->IgnoreParens();
868 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
869 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
870 << (unsigned) CompatIndices.size();
871 for (llvm::SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
872 E = CompatIndices.end(); I != E; ++I) {
873 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
874 diag::note_compat_assoc)
875 << Types[*I]->getTypeLoc().getSourceRange()
876 << Types[*I]->getType();
877 }
878 return ExprError();
879 }
880
881 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
882 // its controlling expression shall have type compatible with exactly one of
883 // the types named in its generic association list."
884 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
885 // We strip parens here because the controlling expression is typically
886 // parenthesized in macro definitions.
887 ControllingExpr = ControllingExpr->IgnoreParens();
888 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
889 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
890 return ExprError();
891 }
892
893 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
894 // type name that is compatible with the type of the controlling expression,
895 // then the result expression of the generic selection is the expression
896 // in that generic association. Otherwise, the result expression of the
897 // generic selection is the expression in the default generic association."
898 unsigned ResultIndex =
899 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
900
901 return Owned(new (Context) GenericSelectionExpr(
902 Context, KeyLoc, ControllingExpr,
903 Types, Exprs, NumAssocs, DefaultLoc,
904 RParenLoc, ContainsUnexpandedParameterPack,
905 ResultIndex));
906}
907
Steve Naroff83895f72007-09-16 03:34:24 +0000908/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000909/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
910/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
911/// multiple tokens. However, the common case is that StringToks points to one
912/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000913///
John McCalldadc5752010-08-24 06:29:42 +0000914ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000915Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000916 assert(NumStringToks && "Must have at least one string!");
917
Chris Lattner8a24e582009-01-16 18:51:42 +0000918 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000919 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000920 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000921
Chris Lattner23b7eb62007-06-15 23:05:46 +0000922 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000923 for (unsigned i = 0; i != NumStringToks; ++i)
924 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000925
Chris Lattner36fc8792008-02-11 00:02:17 +0000926 QualType StrTy = Context.CharTy;
Anders Carlsson6b06e182011-04-06 18:42:48 +0000927 if (Literal.AnyWide)
928 StrTy = Context.getWCharType();
929 else if (Literal.Pascal)
930 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000931
932 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000933 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000934 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000935
Chris Lattner36fc8792008-02-11 00:02:17 +0000936 // Get an array type for the string, according to C99 6.4.5. This includes
937 // the nul terminator character as well as the string length for pascal
938 // strings.
939 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000940 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000941 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000942
Chris Lattner5b183d82006-11-10 05:03:26 +0000943 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +0000944 return Owned(StringLiteral::Create(Context, Literal.GetString(),
945 Literal.GetStringLength(),
Anders Carlsson75245402011-04-14 00:40:03 +0000946 Literal.AnyWide, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +0000947 &StringTokLocs[0],
948 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000949}
950
John McCallc63de662011-02-02 13:00:07 +0000951enum CaptureResult {
952 /// No capture is required.
953 CR_NoCapture,
954
955 /// A capture is required.
956 CR_Capture,
957
John McCall351762c2011-02-07 10:33:21 +0000958 /// A by-ref capture is required.
959 CR_CaptureByRef,
960
John McCallc63de662011-02-02 13:00:07 +0000961 /// An error occurred when trying to capture the given variable.
962 CR_Error
963};
964
965/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +0000966///
John McCallc63de662011-02-02 13:00:07 +0000967/// \param var - the variable referenced
968/// \param DC - the context which we couldn't capture through
969static CaptureResult
John McCall351762c2011-02-07 10:33:21 +0000970diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000971 VarDecl *var, DeclContext *DC) {
972 switch (S.ExprEvalContexts.back().Context) {
973 case Sema::Unevaluated:
974 // The argument will never be evaluated, so don't complain.
975 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +0000976
John McCallc63de662011-02-02 13:00:07 +0000977 case Sema::PotentiallyEvaluated:
978 case Sema::PotentiallyEvaluatedIfUsed:
979 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +0000980
John McCallc63de662011-02-02 13:00:07 +0000981 case Sema::PotentiallyPotentiallyEvaluated:
982 // FIXME: delay these!
983 break;
Chris Lattner497d7b02009-04-21 22:26:47 +0000984 }
Mike Stump11289f42009-09-09 15:08:12 +0000985
John McCallc63de662011-02-02 13:00:07 +0000986 // Don't diagnose about capture if we're not actually in code right
987 // now; in general, there are more appropriate places that will
988 // diagnose this.
989 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
990
John McCall92d627e2011-03-22 23:15:50 +0000991 // Certain madnesses can happen with parameter declarations, which
992 // we want to ignore.
993 if (isa<ParmVarDecl>(var)) {
994 // - If the parameter still belongs to the translation unit, then
995 // we're actually just using one parameter in the declaration of
996 // the next. This is useful in e.g. VLAs.
997 if (isa<TranslationUnitDecl>(var->getDeclContext()))
998 return CR_NoCapture;
999
1000 // - This particular madness can happen in ill-formed default
1001 // arguments; claim it's okay and let downstream code handle it.
1002 if (S.CurContext == var->getDeclContext()->getParent())
1003 return CR_NoCapture;
1004 }
John McCallc63de662011-02-02 13:00:07 +00001005
1006 DeclarationName functionName;
1007 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1008 functionName = fn->getDeclName();
1009 // FIXME: variable from enclosing block that we couldn't capture from!
1010
1011 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1012 << var->getIdentifier() << functionName;
1013 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1014 << var->getIdentifier();
1015
1016 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001017}
1018
John McCall351762c2011-02-07 10:33:21 +00001019/// There is a well-formed capture at a particular scope level;
1020/// propagate it through all the nested blocks.
1021static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1022 const BlockDecl::Capture &capture) {
1023 VarDecl *var = capture.getVariable();
1024
1025 // Update all the inner blocks with the capture information.
1026 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1027 i != e; ++i) {
1028 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1029 innerBlock->Captures.push_back(
1030 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1031 /*nested*/ true, capture.getCopyExpr()));
1032 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1033 }
1034
1035 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1036}
1037
1038/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001039/// given value in the current context requires a variable capture.
1040///
1041/// This also keeps the captures set in the BlockScopeInfo records
1042/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001043static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001044 ValueDecl *value) {
1045 // Only variables ever require capture.
1046 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +00001047 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001048
1049 // Fast path: variables from the current context never require capture.
1050 DeclContext *DC = S.CurContext;
1051 if (var->getDeclContext() == DC) return CR_NoCapture;
1052
1053 // Only variables with local storage require capture.
1054 // FIXME: What about 'const' variables in C++?
1055 if (!var->hasLocalStorage()) return CR_NoCapture;
1056
1057 // Otherwise, we need to capture.
1058
1059 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001060 do {
1061 // Only blocks (and eventually C++0x closures) can capture; other
1062 // scopes don't work.
1063 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001064 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001065
1066 BlockScopeInfo *blockScope =
1067 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1068 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1069
John McCall351762c2011-02-07 10:33:21 +00001070 // Check whether we've already captured it in this block. If so,
1071 // we're done.
1072 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1073 return propagateCapture(S, functionScopesIndex,
1074 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001075
1076 functionScopesIndex--;
1077 DC = cast<BlockDecl>(DC)->getDeclContext();
1078 } while (var->getDeclContext() != DC);
1079
John McCall351762c2011-02-07 10:33:21 +00001080 // Okay, we descended all the way to the block that defines the variable.
1081 // Actually try to capture it.
1082 QualType type = var->getType();
1083
1084 // Prohibit variably-modified types.
1085 if (type->isVariablyModifiedType()) {
1086 S.Diag(loc, diag::err_ref_vm_type);
1087 S.Diag(var->getLocation(), diag::note_declared_at);
1088 return CR_Error;
1089 }
1090
1091 // Prohibit arrays, even in __block variables, but not references to
1092 // them.
1093 if (type->isArrayType()) {
1094 S.Diag(loc, diag::err_ref_array_type);
1095 S.Diag(var->getLocation(), diag::note_declared_at);
1096 return CR_Error;
1097 }
1098
1099 S.MarkDeclarationReferenced(loc, var);
1100
1101 // The BlocksAttr indicates the variable is bound by-reference.
1102 bool byRef = var->hasAttr<BlocksAttr>();
1103
1104 // Build a copy expression.
1105 Expr *copyExpr = 0;
1106 if (!byRef && S.getLangOptions().CPlusPlus &&
1107 !type->isDependentType() && type->isStructureOrClassType()) {
1108 // According to the blocks spec, the capture of a variable from
1109 // the stack requires a const copy constructor. This is not true
1110 // of the copy/move done to move a __block variable to the heap.
1111 type.addConst();
1112
1113 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1114 ExprResult result =
1115 S.PerformCopyInitialization(
1116 InitializedEntity::InitializeBlock(var->getLocation(),
1117 type, false),
1118 loc, S.Owned(declRef));
1119
1120 // Build a full-expression copy expression if initialization
1121 // succeeded and used a non-trivial constructor. Recover from
1122 // errors by pretending that the copy isn't necessary.
1123 if (!result.isInvalid() &&
1124 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1125 result = S.MaybeCreateExprWithCleanups(result);
1126 copyExpr = result.take();
1127 }
1128 }
1129
1130 // We're currently at the declarer; go back to the closure.
1131 functionScopesIndex++;
1132 BlockScopeInfo *blockScope =
1133 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1134
1135 // Build a valid capture in this scope.
1136 blockScope->Captures.push_back(
1137 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1138 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1139
1140 // Propagate that to inner captures if necessary.
1141 return propagateCapture(S, functionScopesIndex,
1142 blockScope->Captures.back());
1143}
1144
1145static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1146 const DeclarationNameInfo &NameInfo,
1147 bool byRef) {
1148 assert(isa<VarDecl>(vd) && "capturing non-variable");
1149
1150 VarDecl *var = cast<VarDecl>(vd);
1151 assert(var->hasLocalStorage() && "capturing non-local");
1152 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1153
1154 QualType exprType = var->getType().getNonReferenceType();
1155
1156 BlockDeclRefExpr *BDRE;
1157 if (!byRef) {
1158 // The variable will be bound by copy; make it const within the
1159 // closure, but record that this was done in the expression.
1160 bool constAdded = !exprType.isConstQualified();
1161 exprType.addConst();
1162
1163 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1164 NameInfo.getLoc(), false,
1165 constAdded);
1166 } else {
1167 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1168 NameInfo.getLoc(), true);
1169 }
1170
1171 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001172}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001173
John McCalldadc5752010-08-24 06:29:42 +00001174ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001175Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001176 SourceLocation Loc,
1177 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001178 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001179 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001180}
1181
John McCallf4cd4f92011-02-09 01:13:10 +00001182/// BuildDeclRefExpr - Build an expression that references a
1183/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001184ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001185Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001186 const DeclarationNameInfo &NameInfo,
1187 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001188 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001189
John McCall086a4642010-11-24 05:12:34 +00001190 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001191 SS? SS->getWithLocInContext(Context)
1192 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001193 D, NameInfo, Ty, VK);
1194
1195 // Just in case we're building an illegal pointer-to-member.
1196 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1197 E->setObjectKind(OK_BitField);
1198
1199 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001200}
1201
John McCallfeb624a2010-11-23 20:48:44 +00001202static ExprResult
1203BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1204 const CXXScopeSpec &SS, FieldDecl *Field,
1205 DeclAccessPair FoundDecl,
1206 const DeclarationNameInfo &MemberNameInfo);
1207
John McCalldadc5752010-08-24 06:29:42 +00001208ExprResult
John McCallf3a88602011-02-03 08:15:49 +00001209Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1210 SourceLocation loc,
1211 IndirectFieldDecl *indirectField,
1212 Expr *baseObjectExpr,
1213 SourceLocation opLoc) {
1214 // First, build the expression that refers to the base object.
1215
1216 bool baseObjectIsPointer = false;
1217 Qualifiers baseQuals;
1218
1219 // Case 1: the base of the indirect field is not a field.
1220 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregore10f36d2011-02-18 02:44:58 +00001221 CXXScopeSpec EmptySS;
John McCallf3a88602011-02-03 08:15:49 +00001222 if (baseVariable) {
1223 assert(baseVariable->getType()->isRecordType());
1224
1225 // In principle we could have a member access expression that
1226 // accesses an anonymous struct/union that's a static member of
1227 // the base object's class. However, under the current standard,
1228 // static data members cannot be anonymous structs or unions.
1229 // Supporting this is as easy as building a MemberExpr here.
1230 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1231
1232 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1233
1234 ExprResult result =
Douglas Gregore10f36d2011-02-18 02:44:58 +00001235 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCallf3a88602011-02-03 08:15:49 +00001236 if (result.isInvalid()) return ExprError();
1237
1238 baseObjectExpr = result.take();
1239 baseObjectIsPointer = false;
1240 baseQuals = baseObjectExpr->getType().getQualifiers();
1241
1242 // Case 2: the base of the indirect field is a field and the user
1243 // wrote a member expression.
1244 } else if (baseObjectExpr) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001245 // The caller provided the base object expression. Determine
1246 // whether its a pointer and whether it adds any qualifiers to the
1247 // anonymous struct/union fields we're looking into.
John McCallf3a88602011-02-03 08:15:49 +00001248 QualType objectType = baseObjectExpr->getType();
1249
1250 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1251 baseObjectIsPointer = true;
1252 objectType = ptr->getPointeeType();
1253 } else {
1254 baseObjectIsPointer = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001255 }
John McCallf3a88602011-02-03 08:15:49 +00001256 baseQuals = objectType.getQualifiers();
1257
1258 // Case 3: the base of the indirect field is a field and we should
1259 // build an implicit member access.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001260 } else {
1261 // We've found a member of an anonymous struct/union that is
1262 // inside a non-anonymous struct/union, so in a well-formed
1263 // program our base object expression is "this".
John McCallf3a88602011-02-03 08:15:49 +00001264 CXXMethodDecl *method = tryCaptureCXXThis();
1265 if (!method) {
1266 Diag(loc, diag::err_invalid_member_use_in_static_method)
1267 << indirectField->getDeclName();
1268 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001269 }
1270
John McCallf3a88602011-02-03 08:15:49 +00001271 // Our base object expression is "this".
1272 baseObjectExpr =
1273 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1274 /*isImplicit=*/ true);
1275 baseObjectIsPointer = true;
1276 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001277 }
1278
1279 // Build the implicit member references to the field of the
1280 // anonymous struct/union.
John McCallf3a88602011-02-03 08:15:49 +00001281 Expr *result = baseObjectExpr;
1282 IndirectFieldDecl::chain_iterator
1283 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCallfeb624a2010-11-23 20:48:44 +00001284
John McCallf3a88602011-02-03 08:15:49 +00001285 // Build the first member access in the chain with full information.
1286 if (!baseVariable) {
1287 FieldDecl *field = cast<FieldDecl>(*FI);
John McCallfeb624a2010-11-23 20:48:44 +00001288
John McCallf3a88602011-02-03 08:15:49 +00001289 // FIXME: use the real found-decl info!
1290 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall8ccfcb52009-09-24 19:53:00 +00001291
John McCallf3a88602011-02-03 08:15:49 +00001292 // Make a nameInfo that properly uses the anonymous name.
1293 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall8ccfcb52009-09-24 19:53:00 +00001294
John McCallf3a88602011-02-03 08:15:49 +00001295 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001296 EmptySS, field, foundDecl,
John McCallf3a88602011-02-03 08:15:49 +00001297 memberNameInfo).take();
1298 baseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +00001299
John McCallf3a88602011-02-03 08:15:49 +00001300 // FIXME: check qualified member access
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001301 }
1302
John McCallf3a88602011-02-03 08:15:49 +00001303 // In all cases, we should now skip the first declaration in the chain.
1304 ++FI;
1305
Douglas Gregore10f36d2011-02-18 02:44:58 +00001306 while (FI != FEnd) {
1307 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCallf3a88602011-02-03 08:15:49 +00001308
1309 // FIXME: these are somewhat meaningless
1310 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1311 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCallf3a88602011-02-03 08:15:49 +00001312
1313 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001314 (FI == FEnd? SS : EmptySS), field,
1315 foundDecl, memberNameInfo)
John McCallf3a88602011-02-03 08:15:49 +00001316 .take();
1317 }
1318
1319 return Owned(result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001320}
1321
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001322/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001323/// possibly a list of template arguments.
1324///
1325/// If this produces template arguments, it is permitted to call
1326/// DecomposeTemplateName.
1327///
1328/// This actually loses a lot of source location information for
1329/// non-standard name kinds; we should consider preserving that in
1330/// some way.
1331static void DecomposeUnqualifiedId(Sema &SemaRef,
1332 const UnqualifiedId &Id,
1333 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001334 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00001335 const TemplateArgumentListInfo *&TemplateArgs) {
1336 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1337 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1338 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1339
1340 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1341 Id.TemplateId->getTemplateArgs(),
1342 Id.TemplateId->NumArgs);
1343 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1344 TemplateArgsPtr.release();
1345
John McCall3e56fd42010-08-23 07:28:44 +00001346 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001347 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1348 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001349 TemplateArgs = &Buffer;
1350 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001351 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001352 TemplateArgs = 0;
1353 }
1354}
1355
John McCall2d74de92009-12-01 22:10:20 +00001356/// Determines if the given class is provably not derived from all of
1357/// the prospective base classes.
1358static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1359 CXXRecordDecl *Record,
1360 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +00001361 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +00001362 return false;
1363
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001364 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +00001365 if (!RD) return false;
1366 Record = cast<CXXRecordDecl>(RD);
1367
John McCall2d74de92009-12-01 22:10:20 +00001368 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1369 E = Record->bases_end(); I != E; ++I) {
1370 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1371 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1372 if (!BaseRT) return false;
1373
1374 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +00001375 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1376 return false;
1377 }
1378
1379 return true;
1380}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001381
John McCall2d74de92009-12-01 22:10:20 +00001382enum IMAKind {
1383 /// The reference is definitely not an instance member access.
1384 IMA_Static,
1385
1386 /// The reference may be an implicit instance member access.
1387 IMA_Mixed,
1388
1389 /// The reference may be to an instance member, but it is invalid if
1390 /// so, because the context is not an instance method.
1391 IMA_Mixed_StaticContext,
1392
1393 /// The reference may be to an instance member, but it is invalid if
1394 /// so, because the context is from an unrelated class.
1395 IMA_Mixed_Unrelated,
1396
1397 /// The reference is definitely an implicit instance member access.
1398 IMA_Instance,
1399
1400 /// The reference may be to an unresolved using declaration.
1401 IMA_Unresolved,
1402
1403 /// The reference may be to an unresolved using declaration and the
1404 /// context is not an instance method.
1405 IMA_Unresolved_StaticContext,
1406
John McCall2d74de92009-12-01 22:10:20 +00001407 /// All possible referrents are instance members and the current
1408 /// context is not an instance method.
1409 IMA_Error_StaticContext,
1410
1411 /// All possible referrents are instance members of an unrelated
1412 /// class.
1413 IMA_Error_Unrelated
1414};
1415
1416/// The given lookup names class member(s) and is not being used for
1417/// an address-of-member expression. Classify the type of access
1418/// according to whether it's possible that this reference names an
1419/// instance member. This is best-effort; it is okay to
1420/// conservatively answer "yes", in which case some errors will simply
1421/// not be caught until template-instantiation.
1422static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1423 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001424 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001425
John McCall87fe5d52010-05-20 01:18:31 +00001426 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +00001427 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001428 (!isa<CXXMethodDecl>(DC) ||
1429 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001430
1431 if (R.isUnresolvableResult())
1432 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1433
1434 // Collect all the declaring classes of instance members we find.
1435 bool hasNonInstance = false;
Sebastian Redl34620312010-11-26 16:28:07 +00001436 bool hasField = false;
John McCall2d74de92009-12-01 22:10:20 +00001437 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1438 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001439 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001440
John McCalla8ae2222010-04-06 21:38:20 +00001441 if (D->isCXXInstanceMember()) {
Sebastian Redl34620312010-11-26 16:28:07 +00001442 if (dyn_cast<FieldDecl>(D))
1443 hasField = true;
1444
John McCall2d74de92009-12-01 22:10:20 +00001445 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001446 Classes.insert(R->getCanonicalDecl());
1447 }
1448 else
1449 hasNonInstance = true;
1450 }
1451
1452 // If we didn't find any instance members, it can't be an implicit
1453 // member reference.
1454 if (Classes.empty())
1455 return IMA_Static;
1456
1457 // If the current context is not an instance method, it can't be
1458 // an implicit member reference.
Sebastian Redl34620312010-11-26 16:28:07 +00001459 if (isStaticContext) {
1460 if (hasNonInstance)
1461 return IMA_Mixed_StaticContext;
1462
1463 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1464 // C++0x [expr.prim.general]p10:
1465 // An id-expression that denotes a non-static data member or non-static
1466 // member function of a class can only be used:
1467 // (...)
1468 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1469 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1470 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1471 if (isUnevaluatedExpression)
1472 return IMA_Mixed_StaticContext;
1473 }
1474
1475 return IMA_Error_StaticContext;
1476 }
John McCall2d74de92009-12-01 22:10:20 +00001477
Argyrios Kyrtzidis36e4ae32011-04-14 00:46:47 +00001478 CXXRecordDecl *
1479 contextClass = cast<CXXMethodDecl>(DC)->getParent()->getCanonicalDecl();
1480
1481 // [class.mfct.non-static]p3:
1482 // ...is used in the body of a non-static member function of class X,
1483 // if name lookup (3.4.1) resolves the name in the id-expression to a
1484 // non-static non-type member of some class C [...]
1485 // ...if C is not X or a base class of X, the class member access expression
1486 // is ill-formed.
1487 if (R.getNamingClass() &&
1488 contextClass != R.getNamingClass()->getCanonicalDecl() &&
1489 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
1490 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1491
John McCall2d74de92009-12-01 22:10:20 +00001492 // If we can prove that the current context is unrelated to all the
1493 // declaring classes, it can't be an implicit member reference (in
1494 // which case it's an error if any of those members are selected).
Argyrios Kyrtzidis36e4ae32011-04-14 00:46:47 +00001495 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
John McCall2d74de92009-12-01 22:10:20 +00001496 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1497
1498 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1499}
1500
1501/// Diagnose a reference to a field with no object available.
1502static void DiagnoseInstanceReference(Sema &SemaRef,
1503 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00001504 NamedDecl *rep,
1505 const DeclarationNameInfo &nameInfo) {
1506 SourceLocation Loc = nameInfo.getLoc();
John McCall2d74de92009-12-01 22:10:20 +00001507 SourceRange Range(Loc);
1508 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1509
John McCallf3a88602011-02-03 08:15:49 +00001510 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCall2d74de92009-12-01 22:10:20 +00001511 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1512 if (MD->isStatic()) {
1513 // "invalid use of member 'x' in static member function"
1514 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCallf3a88602011-02-03 08:15:49 +00001515 << Range << nameInfo.getName();
John McCall2d74de92009-12-01 22:10:20 +00001516 return;
1517 }
1518 }
1519
1520 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCallf3a88602011-02-03 08:15:49 +00001521 << nameInfo.getName() << Range;
John McCall2d74de92009-12-01 22:10:20 +00001522 return;
1523 }
1524
1525 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001526}
1527
John McCalld681c392009-12-16 08:11:27 +00001528/// Diagnose an empty lookup.
1529///
1530/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001531bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1532 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001533 DeclarationName Name = R.getLookupName();
1534
John McCalld681c392009-12-16 08:11:27 +00001535 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001536 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001537 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1538 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001539 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001540 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001541 diagnostic_suggest = diag::err_undeclared_use_suggest;
1542 }
John McCalld681c392009-12-16 08:11:27 +00001543
Douglas Gregor598b08f2009-12-31 05:20:13 +00001544 // If the original lookup was an unqualified lookup, fake an
1545 // unqualified lookup. This is useful when (for example) the
1546 // original lookup would not have found something because it was a
1547 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001548 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001549 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001550 if (isa<CXXRecordDecl>(DC)) {
1551 LookupQualifiedName(R, DC);
1552
1553 if (!R.empty()) {
1554 // Don't give errors about ambiguities in this lookup.
1555 R.suppressDiagnostics();
1556
1557 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1558 bool isInstance = CurMethod &&
1559 CurMethod->isInstance() &&
1560 DC == CurMethod->getParent();
1561
1562 // Give a code modification hint to insert 'this->'.
1563 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1564 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001565 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001566 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1567 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001568 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001569 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001570 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001571 Diag(R.getNameLoc(), diagnostic) << Name
1572 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1573 QualType DepThisType = DepMethod->getThisType(Context);
1574 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1575 R.getNameLoc(), DepThisType, false);
1576 TemplateArgumentListInfo TList;
1577 if (ULE->hasExplicitTemplateArgs())
1578 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001579
Douglas Gregore16af532011-02-28 18:50:33 +00001580 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001581 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001582 CXXDependentScopeMemberExpr *DepExpr =
1583 CXXDependentScopeMemberExpr::Create(
1584 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001585 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001586 R.getLookupNameInfo(), &TList);
1587 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001588 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001589 // FIXME: we should be able to handle this case too. It is correct
1590 // to add this-> here. This is a workaround for PR7947.
1591 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001592 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001593 } else {
John McCalld681c392009-12-16 08:11:27 +00001594 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001595 }
John McCalld681c392009-12-16 08:11:27 +00001596
1597 // Do we really want to note all of these?
1598 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1599 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1600
1601 // Tell the callee to try to recover.
1602 return false;
1603 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001604
1605 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001606 }
1607 }
1608
Douglas Gregor598b08f2009-12-31 05:20:13 +00001609 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001610 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001611 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001612 if (!R.empty()) {
1613 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1614 if (SS.isEmpty())
1615 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1616 << FixItHint::CreateReplacement(R.getNameLoc(),
1617 R.getLookupName().getAsString());
1618 else
1619 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1620 << Name << computeDeclContext(SS, false) << R.getLookupName()
1621 << SS.getRange()
1622 << FixItHint::CreateReplacement(R.getNameLoc(),
1623 R.getLookupName().getAsString());
1624 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1625 Diag(ND->getLocation(), diag::note_previous_decl)
1626 << ND->getDeclName();
1627
1628 // Tell the callee to try to recover.
1629 return false;
1630 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001631
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001632 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1633 // FIXME: If we ended up with a typo for a type name or
1634 // Objective-C class name, we're in trouble because the parser
1635 // is in the wrong place to recover. Suggest the typo
1636 // correction, but don't make it a fix-it since we're not going
1637 // to recover well anyway.
1638 if (SS.isEmpty())
1639 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1640 else
1641 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1642 << Name << computeDeclContext(SS, false) << R.getLookupName()
1643 << SS.getRange();
1644
1645 // Don't try to recover; it won't work.
1646 return true;
1647 }
1648 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001649 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001650 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001651 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001652 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001653 else
Douglas Gregor25363982010-01-01 00:15:04 +00001654 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001655 << Name << computeDeclContext(SS, false) << Corrected
1656 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001657 return true;
1658 }
Douglas Gregor25363982010-01-01 00:15:04 +00001659 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001660 }
1661
1662 // Emit a special diagnostic for failed member lookups.
1663 // FIXME: computing the declaration context might fail here (?)
1664 if (!SS.isEmpty()) {
1665 Diag(R.getNameLoc(), diag::err_no_member)
1666 << Name << computeDeclContext(SS, false)
1667 << SS.getRange();
1668 return true;
1669 }
1670
John McCalld681c392009-12-16 08:11:27 +00001671 // Give up, we can't recover.
1672 Diag(R.getNameLoc(), diagnostic) << Name;
1673 return true;
1674}
1675
Douglas Gregor05fcf842010-11-02 20:36:02 +00001676ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1677 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001678 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1679 if (!IDecl)
1680 return 0;
1681 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1682 if (!ClassImpDecl)
1683 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001684 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001685 if (!property)
1686 return 0;
1687 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001688 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1689 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001690 return 0;
1691 return property;
1692}
1693
Douglas Gregor05fcf842010-11-02 20:36:02 +00001694bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1695 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1696 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1697 if (!IDecl)
1698 return false;
1699 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1700 if (!ClassImpDecl)
1701 return false;
1702 if (ObjCPropertyImplDecl *PIDecl
1703 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1704 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1705 PIDecl->getPropertyIvarDecl())
1706 return false;
1707
1708 return true;
1709}
1710
Fariborz Jahanian18722982010-07-17 00:59:30 +00001711static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001712 LookupResult &Lookup,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001713 IdentifierInfo *II,
1714 SourceLocation NameLoc) {
1715 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001716 bool LookForIvars;
1717 if (Lookup.empty())
1718 LookForIvars = true;
1719 else if (CurMeth->isClassMethod())
1720 LookForIvars = false;
1721 else
1722 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001723 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1724 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001725 if (!LookForIvars)
1726 return 0;
1727
Fariborz Jahanian18722982010-07-17 00:59:30 +00001728 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1729 if (!IDecl)
1730 return 0;
1731 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001732 if (!ClassImpDecl)
1733 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001734 bool DynamicImplSeen = false;
1735 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1736 if (!property)
1737 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001738 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001739 DynamicImplSeen =
1740 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001741 // property implementation has a designated ivar. No need to assume a new
1742 // one.
1743 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1744 return 0;
1745 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001746 if (!DynamicImplSeen) {
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001747 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1748 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001749 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001750 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001751 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001752 (Expr *)0, true);
1753 ClassImpDecl->addDecl(Ivar);
1754 IDecl->makeDeclVisibleInContext(Ivar, false);
1755 property->setPropertyIvarDecl(Ivar);
1756 return Ivar;
1757 }
1758 return 0;
1759}
1760
John McCalldadc5752010-08-24 06:29:42 +00001761ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001762 CXXScopeSpec &SS,
1763 UnqualifiedId &Id,
1764 bool HasTrailingLParen,
1765 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001766 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1767 "cannot be direct & operand and have a trailing lparen");
1768
1769 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001770 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001771
John McCall10eae182009-11-30 22:42:35 +00001772 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001773
1774 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001775 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001776 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001777 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001778
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001779 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001780 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001781 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001782
John McCalle66edc12009-11-24 19:00:30 +00001783 // C++ [temp.dep.expr]p3:
1784 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001785 // -- an identifier that was declared with a dependent type,
1786 // (note: handled after lookup)
1787 // -- a template-id that is dependent,
1788 // (note: handled in BuildTemplateIdExpr)
1789 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001790 // -- a nested-name-specifier that contains a class-name that
1791 // names a dependent type.
1792 // Determine whether this is a member of an unknown specialization;
1793 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001794 bool DependentID = false;
1795 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1796 Name.getCXXNameType()->isDependentType()) {
1797 DependentID = true;
1798 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001799 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001800 if (RequireCompleteDeclContext(SS, DC))
1801 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001802 } else {
1803 DependentID = true;
1804 }
1805 }
1806
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001807 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001808 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001809 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001810
Fariborz Jahanian86151342010-07-22 23:33:21 +00001811 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001812 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001813 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001814 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001815 // Lookup the template name again to correctly establish the context in
1816 // which it was found. This is really unfortunate as we already did the
1817 // lookup to determine that it was a template name in the first place. If
1818 // this becomes a performance hit, we can work harder to preserve those
1819 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001820 bool MemberOfUnknownSpecialization;
1821 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1822 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001823
1824 if (MemberOfUnknownSpecialization ||
1825 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1826 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1827 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001828 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001829 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001830 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001831
Douglas Gregora5226932011-02-04 13:35:07 +00001832 // If the result might be in a dependent base class, this is a dependent
1833 // id-expression.
1834 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1835 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1836 TemplateArgs);
1837
John McCalle66edc12009-11-24 19:00:30 +00001838 // If this reference is in an Objective-C method, then we need to do
1839 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001840 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001841 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001842 if (E.isInvalid())
1843 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001844
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001845 if (Expr *Ex = E.takeAs<Expr>())
1846 return Owned(Ex);
1847
1848 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001849 if (getLangOptions().ObjCDefaultSynthProperties &&
1850 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001851 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1852 if (const ObjCPropertyDecl *Property =
1853 canSynthesizeProvisionalIvar(II)) {
1854 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1855 Diag(Property->getLocation(), diag::note_property_declare);
1856 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001857 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1858 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001859 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001860 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001861 // for further use, this must be set to false if in class method.
1862 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001863 }
Chris Lattner59a25942008-03-31 00:36:02 +00001864 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001865
John McCalle66edc12009-11-24 19:00:30 +00001866 if (R.isAmbiguous())
1867 return ExprError();
1868
Douglas Gregor171c45a2009-02-18 21:56:37 +00001869 // Determine whether this name might be a candidate for
1870 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001871 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001872
John McCalle66edc12009-11-24 19:00:30 +00001873 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001874 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001875 // in C90, extension in C99, forbidden in C++).
1876 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1877 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1878 if (D) R.addDecl(D);
1879 }
1880
1881 // If this name wasn't predeclared and if this is not a function
1882 // call, diagnose the problem.
1883 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001884 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001885 return ExprError();
1886
1887 assert(!R.empty() &&
1888 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001889
1890 // If we found an Objective-C instance variable, let
1891 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001892 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001893 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1894 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001895 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001896 assert(E.isInvalid() || E.get());
1897 return move(E);
1898 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001899 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001900 }
Mike Stump11289f42009-09-09 15:08:12 +00001901
John McCalle66edc12009-11-24 19:00:30 +00001902 // This is guaranteed from this point on.
1903 assert(!R.empty() || ADL);
1904
John McCall2d74de92009-12-01 22:10:20 +00001905 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001906 // C++ [class.mfct.non-static]p3:
1907 // When an id-expression that is not part of a class member access
1908 // syntax and not used to form a pointer to member is used in the
1909 // body of a non-static member function of class X, if name lookup
1910 // resolves the name in the id-expression to a non-static non-type
1911 // member of some class C, the id-expression is transformed into a
1912 // class member access expression using (*this) as the
1913 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001914 //
1915 // But we don't actually need to do this for '&' operands if R
1916 // resolved to a function or overloaded function set, because the
1917 // expression is ill-formed if it actually works out to be a
1918 // non-static member function:
1919 //
1920 // C++ [expr.ref]p4:
1921 // Otherwise, if E1.E2 refers to a non-static member function. . .
1922 // [t]he expression can be used only as the left-hand operand of a
1923 // member function call.
1924 //
1925 // There are other safeguards against such uses, but it's important
1926 // to get this right here so that we don't end up making a
1927 // spuriously dependent expression if we're inside a dependent
1928 // instance method.
John McCall57500772009-12-16 12:17:52 +00001929 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001930 bool MightBeImplicitMember;
1931 if (!isAddressOfOperand)
1932 MightBeImplicitMember = true;
1933 else if (!SS.isEmpty())
1934 MightBeImplicitMember = false;
1935 else if (R.isOverloadedResult())
1936 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001937 else if (R.isUnresolvableResult())
1938 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001939 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001940 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1941 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001942
1943 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001944 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001945 }
1946
John McCalle66edc12009-11-24 19:00:30 +00001947 if (TemplateArgs)
1948 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001949
John McCalle66edc12009-11-24 19:00:30 +00001950 return BuildDeclarationNameExpr(SS, R, ADL);
1951}
1952
John McCall57500772009-12-16 12:17:52 +00001953/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00001954ExprResult
John McCall57500772009-12-16 12:17:52 +00001955Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1956 LookupResult &R,
1957 const TemplateArgumentListInfo *TemplateArgs) {
1958 switch (ClassifyImplicitMemberAccess(*this, R)) {
1959 case IMA_Instance:
1960 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1961
John McCall57500772009-12-16 12:17:52 +00001962 case IMA_Mixed:
1963 case IMA_Mixed_Unrelated:
1964 case IMA_Unresolved:
1965 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1966
1967 case IMA_Static:
1968 case IMA_Mixed_StaticContext:
1969 case IMA_Unresolved_StaticContext:
1970 if (TemplateArgs)
1971 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1972 return BuildDeclarationNameExpr(SS, R, false);
1973
1974 case IMA_Error_StaticContext:
1975 case IMA_Error_Unrelated:
John McCallf3a88602011-02-03 08:15:49 +00001976 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1977 R.getLookupNameInfo());
John McCall57500772009-12-16 12:17:52 +00001978 return ExprError();
1979 }
1980
1981 llvm_unreachable("unexpected instance member access kind");
1982 return ExprError();
1983}
1984
John McCall10eae182009-11-30 22:42:35 +00001985/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1986/// declaration name, generally during template instantiation.
1987/// There's a large number of things which don't need to be done along
1988/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001989ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001990Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001991 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001992 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001993 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001994 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001995
John McCall0b66eb32010-05-01 00:40:08 +00001996 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001997 return ExprError();
1998
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001999 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00002000 LookupQualifiedName(R, DC);
2001
2002 if (R.isAmbiguous())
2003 return ExprError();
2004
2005 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002006 Diag(NameInfo.getLoc(), diag::err_no_member)
2007 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002008 return ExprError();
2009 }
2010
2011 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
2012}
2013
2014/// LookupInObjCMethod - The parser has read a name in, and Sema has
2015/// detected that we're currently inside an ObjC method. Perform some
2016/// additional lookup.
2017///
2018/// Ideally, most of this would be done by lookup, but there's
2019/// actually quite a lot of extra work involved.
2020///
2021/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00002022ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002023Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00002024 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00002025 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00002026 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00002027
John McCalle66edc12009-11-24 19:00:30 +00002028 // There are two cases to handle here. 1) scoped lookup could have failed,
2029 // in which case we should look for an ivar. 2) scoped lookup could have
2030 // found a decl, but that decl is outside the current instance method (i.e.
2031 // a global variable). In these two cases, we do a lookup for an ivar with
2032 // this name, if the lookup sucedes, we replace it our current decl.
2033
2034 // If we're in a class method, we don't normally want to look for
2035 // ivars. But if we don't find anything else, and there's an
2036 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00002037 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00002038
2039 bool LookForIvars;
2040 if (Lookup.empty())
2041 LookForIvars = true;
2042 else if (IsClassMethod)
2043 LookForIvars = false;
2044 else
2045 LookForIvars = (Lookup.isSingleResult() &&
2046 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00002047 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00002048 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00002049 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00002050 ObjCInterfaceDecl *ClassDeclared;
2051 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2052 // Diagnose using an ivar in a class method.
2053 if (IsClassMethod)
2054 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2055 << IV->getDeclName());
2056
2057 // If we're referencing an invalid decl, just return this as a silent
2058 // error node. The error diagnostic was already emitted on the decl.
2059 if (IV->isInvalidDecl())
2060 return ExprError();
2061
2062 // Check if referencing a field with __attribute__((deprecated)).
2063 if (DiagnoseUseOfDecl(IV, Loc))
2064 return ExprError();
2065
2066 // Diagnose the use of an ivar outside of the declaring class.
2067 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2068 ClassDeclared != IFace)
2069 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2070
2071 // FIXME: This should use a new expr for a direct reference, don't
2072 // turn this into Self->ivar, just return a BareIVarExpr or something.
2073 IdentifierInfo &II = Context.Idents.get("self");
2074 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002075 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00002076 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00002077 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00002078 SelfName, false, false);
2079 if (SelfExpr.isInvalid())
2080 return ExprError();
2081
John Wiegley01296292011-04-08 18:41:53 +00002082 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2083 if (SelfExpr.isInvalid())
2084 return ExprError();
John McCall27584242010-12-06 20:48:59 +00002085
John McCalle66edc12009-11-24 19:00:30 +00002086 MarkDeclarationReferenced(Loc, IV);
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00002087 Expr *base = SelfExpr.take();
2088 base = base->IgnoreParenImpCasts();
2089 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(base)) {
2090 const NamedDecl *ND = DE->getDecl();
2091 if (!isa<ImplicitParamDecl>(ND)) {
Fariborz Jahanian66a6c062011-04-15 17:04:42 +00002092 // relax the rule such that it is allowed to have a shadow 'self'
2093 // where stand-alone ivar can be found in this 'self' object.
2094 // This is to match gcc's behavior.
2095 ObjCInterfaceDecl *selfIFace = 0;
2096 if (const ObjCObjectPointerType *OPT =
2097 base->getType()->getAsObjCInterfacePointerType())
2098 selfIFace = OPT->getInterfaceDecl();
2099 if (!selfIFace ||
2100 !selfIFace->lookupInstanceVariable(IV->getIdentifier())) {
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00002101 Diag(Loc, diag::error_implicit_ivar_access)
2102 << IV->getDeclName();
2103 Diag(ND->getLocation(), diag::note_declared_at);
2104 return ExprError();
2105 }
Fariborz Jahanian66a6c062011-04-15 17:04:42 +00002106 }
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00002107 }
John McCalle66edc12009-11-24 19:00:30 +00002108 return Owned(new (Context)
2109 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00002110 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00002111 }
Chris Lattner87313662010-04-12 05:10:17 +00002112 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00002113 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00002114 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00002115 ObjCInterfaceDecl *ClassDeclared;
2116 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2117 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2118 IFace == ClassDeclared)
2119 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2120 }
2121 }
2122
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002123 if (Lookup.empty() && II && AllowBuiltinCreation) {
2124 // FIXME. Consolidate this with similar code in LookupName.
2125 if (unsigned BuiltinID = II->getBuiltinID()) {
2126 if (!(getLangOptions().CPlusPlus &&
2127 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2128 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2129 S, Lookup.isForRedeclaration(),
2130 Lookup.getNameLoc());
2131 if (D) Lookup.addDecl(D);
2132 }
2133 }
2134 }
John McCalle66edc12009-11-24 19:00:30 +00002135 // Sentinel value saying that we didn't do anything special.
2136 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00002137}
John McCalld14a8642009-11-21 08:51:07 +00002138
John McCall16df1e52010-03-30 21:47:33 +00002139/// \brief Cast a base object to a member's actual type.
2140///
2141/// Logically this happens in three phases:
2142///
2143/// * First we cast from the base type to the naming class.
2144/// The naming class is the class into which we were looking
2145/// when we found the member; it's the qualifier type if a
2146/// qualifier was provided, and otherwise it's the base type.
2147///
2148/// * Next we cast from the naming class to the declaring class.
2149/// If the member we found was brought into a class's scope by
2150/// a using declaration, this is that class; otherwise it's
2151/// the class declaring the member.
2152///
2153/// * Finally we cast from the declaring class to the "true"
2154/// declaring class of the member. This conversion does not
2155/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00002156ExprResult
2157Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002158 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002159 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002160 NamedDecl *Member) {
2161 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2162 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00002163 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002164
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002165 QualType DestRecordType;
2166 QualType DestType;
2167 QualType FromRecordType;
2168 QualType FromType = From->getType();
2169 bool PointerConversions = false;
2170 if (isa<FieldDecl>(Member)) {
2171 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002172
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002173 if (FromType->getAs<PointerType>()) {
2174 DestType = Context.getPointerType(DestRecordType);
2175 FromRecordType = FromType->getPointeeType();
2176 PointerConversions = true;
2177 } else {
2178 DestType = DestRecordType;
2179 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002180 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002181 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2182 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00002183 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002184
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002185 DestType = Method->getThisType(Context);
2186 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002187
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002188 if (FromType->getAs<PointerType>()) {
2189 FromRecordType = FromType->getPointeeType();
2190 PointerConversions = true;
2191 } else {
2192 FromRecordType = FromType;
2193 DestType = DestRecordType;
2194 }
2195 } else {
2196 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002197 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002198 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002199
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002200 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002201 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002202
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002203 // If the unqualified types are the same, no conversion is necessary.
2204 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002205 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002206
John McCall16df1e52010-03-30 21:47:33 +00002207 SourceRange FromRange = From->getSourceRange();
2208 SourceLocation FromLoc = FromRange.getBegin();
2209
John McCall2536c6d2010-08-25 10:28:54 +00002210 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002211
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002212 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002213 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002214 // class name.
2215 //
2216 // If the member was a qualified name and the qualified referred to a
2217 // specific base subobject type, we'll cast to that intermediate type
2218 // first and then to the object in which the member is declared. That allows
2219 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2220 //
2221 // class Base { public: int x; };
2222 // class Derived1 : public Base { };
2223 // class Derived2 : public Base { };
2224 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2225 //
2226 // void VeryDerived::f() {
2227 // x = 17; // error: ambiguous base subobjects
2228 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2229 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002230 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002231 QualType QType = QualType(Qualifier->getAsType(), 0);
2232 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2233 assert(QType->isRecordType() && "lookup done with non-record type");
2234
2235 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2236
2237 // In C++98, the qualifier type doesn't actually have to be a base
2238 // type of the object type, in which case we just ignore it.
2239 // Otherwise build the appropriate casts.
2240 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002241 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002242 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002243 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002244 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002245
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002246 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002247 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002248 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2249 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002250
2251 FromType = QType;
2252 FromRecordType = QRecordType;
2253
2254 // If the qualifier type was the same as the destination type,
2255 // we're done.
2256 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002257 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002258 }
2259 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002260
John McCall16df1e52010-03-30 21:47:33 +00002261 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002262
John McCall16df1e52010-03-30 21:47:33 +00002263 // If we actually found the member through a using declaration, cast
2264 // down to the using declaration's type.
2265 //
2266 // Pointer equality is fine here because only one declaration of a
2267 // class ever has member declarations.
2268 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2269 assert(isa<UsingShadowDecl>(FoundDecl));
2270 QualType URecordType = Context.getTypeDeclType(
2271 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2272
2273 // We only need to do this if the naming-class to declaring-class
2274 // conversion is non-trivial.
2275 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2276 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002277 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002278 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002279 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002280 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002281
John McCall16df1e52010-03-30 21:47:33 +00002282 QualType UType = URecordType;
2283 if (PointerConversions)
2284 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002285 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2286 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002287 FromType = UType;
2288 FromRecordType = URecordType;
2289 }
2290
2291 // We don't do access control for the conversion from the
2292 // declaring class to the true declaring class.
2293 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002294 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002295
John McCallcf142162010-08-07 06:22:56 +00002296 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002297 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2298 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002299 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002300 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002301
John Wiegley01296292011-04-08 18:41:53 +00002302 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2303 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002304}
Douglas Gregor3256d042009-06-30 15:47:41 +00002305
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002306/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00002307static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00002308 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00002309 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002310 const DeclarationNameInfo &MemberNameInfo,
2311 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00002312 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00002313 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregorea972d32011-02-28 21:54:11 +00002314 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002315 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002316 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00002317}
2318
John McCallfeb624a2010-11-23 20:48:44 +00002319static ExprResult
2320BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2321 const CXXScopeSpec &SS, FieldDecl *Field,
2322 DeclAccessPair FoundDecl,
2323 const DeclarationNameInfo &MemberNameInfo) {
2324 // x.a is an l-value if 'a' has a reference type. Otherwise:
2325 // x.a is an l-value/x-value/pr-value if the base is (and note
2326 // that *x is always an l-value), except that if the base isn't
2327 // an ordinary object then we must have an rvalue.
2328 ExprValueKind VK = VK_LValue;
2329 ExprObjectKind OK = OK_Ordinary;
2330 if (!IsArrow) {
2331 if (BaseExpr->getObjectKind() == OK_Ordinary)
2332 VK = BaseExpr->getValueKind();
2333 else
2334 VK = VK_RValue;
2335 }
2336 if (VK != VK_RValue && Field->isBitField())
2337 OK = OK_BitField;
2338
2339 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2340 QualType MemberType = Field->getType();
2341 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2342 MemberType = Ref->getPointeeType();
2343 VK = VK_LValue;
2344 } else {
2345 QualType BaseType = BaseExpr->getType();
2346 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2347
2348 Qualifiers BaseQuals = BaseType.getQualifiers();
2349
2350 // GC attributes are never picked up by members.
2351 BaseQuals.removeObjCGCAttr();
2352
2353 // CVR attributes from the base are picked up by members,
2354 // except that 'mutable' members don't pick up 'const'.
2355 if (Field->isMutable()) BaseQuals.removeConst();
2356
2357 Qualifiers MemberQuals
2358 = S.Context.getCanonicalType(MemberType).getQualifiers();
2359
2360 // TR 18037 does not allow fields to be declared with address spaces.
2361 assert(!MemberQuals.hasAddressSpace());
2362
2363 Qualifiers Combined = BaseQuals + MemberQuals;
2364 if (Combined != MemberQuals)
2365 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2366 }
2367
2368 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
John Wiegley01296292011-04-08 18:41:53 +00002369 ExprResult Base =
2370 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2371 FoundDecl, Field);
2372 if (Base.isInvalid())
John McCallfeb624a2010-11-23 20:48:44 +00002373 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00002374 return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
John McCallfeb624a2010-11-23 20:48:44 +00002375 Field, FoundDecl, MemberNameInfo,
2376 MemberType, VK, OK));
2377}
2378
John McCall2d74de92009-12-01 22:10:20 +00002379/// Builds an implicit member access expression. The current context
2380/// is known to be an instance method, and the given unqualified lookup
2381/// set is known to contain only instance members, at least one of which
2382/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002383ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002384Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2385 LookupResult &R,
2386 const TemplateArgumentListInfo *TemplateArgs,
2387 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002388 assert(!R.empty() && !R.isAmbiguous());
2389
John McCallf3a88602011-02-03 08:15:49 +00002390 SourceLocation loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002391
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002392 // We may have found a field within an anonymous union or struct
2393 // (C++ [class.union]).
John McCalle66edc12009-11-24 19:00:30 +00002394 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002395 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCallf3a88602011-02-03 08:15:49 +00002396 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002397
John McCallf3a88602011-02-03 08:15:49 +00002398 // If this is known to be an instance access, go ahead and build an
2399 // implicit 'this' expression now.
John McCall2d74de92009-12-01 22:10:20 +00002400 // 'this' expression now.
John McCallf3a88602011-02-03 08:15:49 +00002401 CXXMethodDecl *method = tryCaptureCXXThis();
2402 assert(method && "didn't correctly pre-flight capture of 'this'");
2403
2404 QualType thisType = method->getThisType(Context);
2405 Expr *baseExpr = 0; // null signifies implicit access
John McCall2d74de92009-12-01 22:10:20 +00002406 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002407 SourceLocation Loc = R.getNameLoc();
2408 if (SS.getRange().isValid())
2409 Loc = SS.getRange().getBegin();
John McCallf3a88602011-02-03 08:15:49 +00002410 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002411 }
2412
John McCallf3a88602011-02-03 08:15:49 +00002413 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCall2d74de92009-12-01 22:10:20 +00002414 /*OpLoc*/ SourceLocation(),
2415 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002416 SS,
2417 /*FirstQualifierInScope*/ 0,
2418 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002419}
2420
John McCalle66edc12009-11-24 19:00:30 +00002421bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002422 const LookupResult &R,
2423 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002424 // Only when used directly as the postfix-expression of a call.
2425 if (!HasTrailingLParen)
2426 return false;
2427
2428 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002429 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002430 return false;
2431
2432 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002433 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002434 return false;
2435
2436 // Turn off ADL when we find certain kinds of declarations during
2437 // normal lookup:
2438 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2439 NamedDecl *D = *I;
2440
2441 // C++0x [basic.lookup.argdep]p3:
2442 // -- a declaration of a class member
2443 // Since using decls preserve this property, we check this on the
2444 // original decl.
John McCall57500772009-12-16 12:17:52 +00002445 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002446 return false;
2447
2448 // C++0x [basic.lookup.argdep]p3:
2449 // -- a block-scope function declaration that is not a
2450 // using-declaration
2451 // NOTE: we also trigger this for function templates (in fact, we
2452 // don't check the decl type at all, since all other decl types
2453 // turn off ADL anyway).
2454 if (isa<UsingShadowDecl>(D))
2455 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2456 else if (D->getDeclContext()->isFunctionOrMethod())
2457 return false;
2458
2459 // C++0x [basic.lookup.argdep]p3:
2460 // -- a declaration that is neither a function or a function
2461 // template
2462 // And also for builtin functions.
2463 if (isa<FunctionDecl>(D)) {
2464 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2465
2466 // But also builtin functions.
2467 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2468 return false;
2469 } else if (!isa<FunctionTemplateDecl>(D))
2470 return false;
2471 }
2472
2473 return true;
2474}
2475
2476
John McCalld14a8642009-11-21 08:51:07 +00002477/// Diagnoses obvious problems with the use of the given declaration
2478/// as an expression. This is only actually called for lookups that
2479/// were not overloaded, and it doesn't promise that the declaration
2480/// will in fact be used.
2481static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002482 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002483 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2484 return true;
2485 }
2486
2487 if (isa<ObjCInterfaceDecl>(D)) {
2488 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2489 return true;
2490 }
2491
2492 if (isa<NamespaceDecl>(D)) {
2493 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2494 return true;
2495 }
2496
2497 return false;
2498}
2499
John McCalldadc5752010-08-24 06:29:42 +00002500ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002501Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002502 LookupResult &R,
2503 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002504 // If this is a single, fully-resolved result and we don't need ADL,
2505 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002506 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002507 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2508 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002509
2510 // We only need to check the declaration if there's exactly one
2511 // result, because in the overloaded case the results can only be
2512 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002513 if (R.isSingleResult() &&
2514 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002515 return ExprError();
2516
John McCall58cc69d2010-01-27 01:50:18 +00002517 // Otherwise, just build an unresolved lookup expression. Suppress
2518 // any lookup-related diagnostics; we'll hash these out later, when
2519 // we've picked a target.
2520 R.suppressDiagnostics();
2521
John McCalld14a8642009-11-21 08:51:07 +00002522 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002523 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002524 SS.getWithLocInContext(Context),
2525 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002526 NeedsADL, R.isOverloadedResult(),
2527 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002528
2529 return Owned(ULE);
2530}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002531
John McCalld14a8642009-11-21 08:51:07 +00002532/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002533ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002534Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002535 const DeclarationNameInfo &NameInfo,
2536 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002537 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002538 assert(!isa<FunctionTemplateDecl>(D) &&
2539 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002540
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002541 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002542 if (CheckDeclInExpr(*this, Loc, D))
2543 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002544
Douglas Gregore7488b92009-12-01 16:58:18 +00002545 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2546 // Specifically diagnose references to class templates that are missing
2547 // a template argument list.
2548 Diag(Loc, diag::err_template_decl_ref)
2549 << Template << SS.getRange();
2550 Diag(Template->getLocation(), diag::note_template_decl_here);
2551 return ExprError();
2552 }
2553
2554 // Make sure that we're referring to a value.
2555 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2556 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002557 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002558 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002559 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002560 return ExprError();
2561 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002562
Douglas Gregor171c45a2009-02-18 21:56:37 +00002563 // Check whether this declaration can be used. Note that we suppress
2564 // this check when we're going to perform argument-dependent lookup
2565 // on this function name, because this might not be the function
2566 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002567 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002568 return ExprError();
2569
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002570 // Only create DeclRefExpr's for valid Decl's.
2571 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002572 return ExprError();
2573
John McCallf3a88602011-02-03 08:15:49 +00002574 // Handle members of anonymous structs and unions. If we got here,
2575 // and the reference is to a class member indirect field, then this
2576 // must be the subject of a pointer-to-member expression.
2577 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2578 if (!indirectField->isCXXClassMember())
2579 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2580 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002581
Chris Lattner2a9d9892008-10-20 05:16:36 +00002582 // If the identifier reference is inside a block, and it refers to a value
2583 // that is outside the block, create a BlockDeclRefExpr instead of a
2584 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2585 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002586 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002587 // We do not do this for things like enum constants, global variables, etc,
2588 // as they do not get snapshotted.
2589 //
John McCall351762c2011-02-07 10:33:21 +00002590 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002591 case CR_Error:
2592 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002593
John McCallc63de662011-02-02 13:00:07 +00002594 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002595 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2596 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2597
2598 case CR_CaptureByRef:
2599 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2600 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002601
2602 case CR_NoCapture: {
2603 // If this reference is not in a block or if the referenced
2604 // variable is within the block, create a normal DeclRefExpr.
2605
2606 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002607 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002608
2609 switch (D->getKind()) {
2610 // Ignore all the non-ValueDecl kinds.
2611#define ABSTRACT_DECL(kind)
2612#define VALUE(type, base)
2613#define DECL(type, base) \
2614 case Decl::type:
2615#include "clang/AST/DeclNodes.inc"
2616 llvm_unreachable("invalid value decl kind");
2617 return ExprError();
2618
2619 // These shouldn't make it here.
2620 case Decl::ObjCAtDefsField:
2621 case Decl::ObjCIvar:
2622 llvm_unreachable("forming non-member reference to ivar?");
2623 return ExprError();
2624
2625 // Enum constants are always r-values and never references.
2626 // Unresolved using declarations are dependent.
2627 case Decl::EnumConstant:
2628 case Decl::UnresolvedUsingValue:
2629 valueKind = VK_RValue;
2630 break;
2631
2632 // Fields and indirect fields that got here must be for
2633 // pointer-to-member expressions; we just call them l-values for
2634 // internal consistency, because this subexpression doesn't really
2635 // exist in the high-level semantics.
2636 case Decl::Field:
2637 case Decl::IndirectField:
2638 assert(getLangOptions().CPlusPlus &&
2639 "building reference to field in C?");
2640
2641 // These can't have reference type in well-formed programs, but
2642 // for internal consistency we do this anyway.
2643 type = type.getNonReferenceType();
2644 valueKind = VK_LValue;
2645 break;
2646
2647 // Non-type template parameters are either l-values or r-values
2648 // depending on the type.
2649 case Decl::NonTypeTemplateParm: {
2650 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2651 type = reftype->getPointeeType();
2652 valueKind = VK_LValue; // even if the parameter is an r-value reference
2653 break;
2654 }
2655
2656 // For non-references, we need to strip qualifiers just in case
2657 // the template parameter was declared as 'const int' or whatever.
2658 valueKind = VK_RValue;
2659 type = type.getUnqualifiedType();
2660 break;
2661 }
2662
2663 case Decl::Var:
2664 // In C, "extern void blah;" is valid and is an r-value.
2665 if (!getLangOptions().CPlusPlus &&
2666 !type.hasQualifiers() &&
2667 type->isVoidType()) {
2668 valueKind = VK_RValue;
2669 break;
2670 }
2671 // fallthrough
2672
2673 case Decl::ImplicitParam:
2674 case Decl::ParmVar:
2675 // These are always l-values.
2676 valueKind = VK_LValue;
2677 type = type.getNonReferenceType();
2678 break;
2679
2680 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002681 const FunctionType *fty = type->castAs<FunctionType>();
2682
2683 // If we're referring to a function with an __unknown_anytype
2684 // result type, make the entire expression __unknown_anytype.
2685 if (fty->getResultType() == Context.UnknownAnyTy) {
2686 type = Context.UnknownAnyTy;
2687 valueKind = VK_RValue;
2688 break;
2689 }
2690
John McCallf4cd4f92011-02-09 01:13:10 +00002691 // Functions are l-values in C++.
2692 if (getLangOptions().CPlusPlus) {
2693 valueKind = VK_LValue;
2694 break;
2695 }
2696
2697 // C99 DR 316 says that, if a function type comes from a
2698 // function definition (without a prototype), that type is only
2699 // used for checking compatibility. Therefore, when referencing
2700 // the function, we pretend that we don't have the full function
2701 // type.
John McCall2979fe02011-04-12 00:42:48 +00002702 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2703 isa<FunctionProtoType>(fty))
2704 type = Context.getFunctionNoProtoType(fty->getResultType(),
2705 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002706
2707 // Functions are r-values in C.
2708 valueKind = VK_RValue;
2709 break;
2710 }
2711
2712 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002713 // If we're referring to a method with an __unknown_anytype
2714 // result type, make the entire expression __unknown_anytype.
2715 // This should only be possible with a type written directly.
2716 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2717 if (proto->getResultType() == Context.UnknownAnyTy) {
2718 type = Context.UnknownAnyTy;
2719 valueKind = VK_RValue;
2720 break;
2721 }
2722
John McCallf4cd4f92011-02-09 01:13:10 +00002723 // C++ methods are l-values if static, r-values if non-static.
2724 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2725 valueKind = VK_LValue;
2726 break;
2727 }
2728 // fallthrough
2729
2730 case Decl::CXXConversion:
2731 case Decl::CXXDestructor:
2732 case Decl::CXXConstructor:
2733 valueKind = VK_RValue;
2734 break;
2735 }
2736
2737 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2738 }
2739
John McCallc63de662011-02-02 13:00:07 +00002740 }
John McCall7decc9e2010-11-18 06:31:45 +00002741
John McCall351762c2011-02-07 10:33:21 +00002742 llvm_unreachable("unknown capture result");
2743 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002744}
Chris Lattnere168f762006-11-10 05:29:30 +00002745
John McCall2979fe02011-04-12 00:42:48 +00002746ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002747 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002748
Chris Lattnere168f762006-11-10 05:29:30 +00002749 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002750 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002751 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2752 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2753 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002754 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002755
Chris Lattnera81a0272008-01-12 08:14:25 +00002756 // Pre-defined identifiers are of type char[x], where x is the length of the
2757 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002758
Anders Carlsson2fb08242009-09-08 18:24:21 +00002759 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002760 if (!currentDecl && getCurBlock())
2761 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002762 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002763 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002764 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002765 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002766
Anders Carlsson0b209a82009-09-11 01:22:35 +00002767 QualType ResTy;
2768 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2769 ResTy = Context.DependentTy;
2770 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002771 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002772
Anders Carlsson0b209a82009-09-11 01:22:35 +00002773 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002774 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002775 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2776 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002777 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002778}
2779
John McCalldadc5752010-08-24 06:29:42 +00002780ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002781 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002782 bool Invalid = false;
2783 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2784 if (Invalid)
2785 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002786
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002787 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2788 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002789 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002790 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002791
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002792 QualType Ty;
2793 if (!getLangOptions().CPlusPlus)
2794 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2795 else if (Literal.isWide())
2796 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002797 else if (Literal.isMultiChar())
2798 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002799 else
2800 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002801
Sebastian Redl20614a72009-01-20 22:23:13 +00002802 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2803 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002804 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002805}
2806
John McCalldadc5752010-08-24 06:29:42 +00002807ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002808 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002809 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2810 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002811 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002812 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002813 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002814 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002815 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002816
Chris Lattner23b7eb62007-06-15 23:05:46 +00002817 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002818 // Add padding so that NumericLiteralParser can overread by one character.
2819 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002820 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002821
Chris Lattner67ca9252007-05-21 01:08:44 +00002822 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002823 bool Invalid = false;
2824 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2825 if (Invalid)
2826 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002827
Mike Stump11289f42009-09-09 15:08:12 +00002828 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002829 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002830 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002831 return ExprError();
2832
Chris Lattner1c20a172007-08-26 03:42:43 +00002833 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002834
Chris Lattner1c20a172007-08-26 03:42:43 +00002835 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002836 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002837 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002838 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002839 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002840 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002841 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002842 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002843
2844 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2845
John McCall53b93a02009-12-24 09:08:04 +00002846 using llvm::APFloat;
2847 APFloat Val(Format);
2848
2849 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002850
2851 // Overflow is always an error, but underflow is only an error if
2852 // we underflowed to zero (APFloat reports denormals as underflow).
2853 if ((result & APFloat::opOverflow) ||
2854 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002855 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002856 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002857 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002858 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002859 APFloat::getLargest(Format).toString(buffer);
2860 } else {
John McCall62abc942010-02-26 23:35:57 +00002861 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002862 APFloat::getSmallest(Format).toString(buffer);
2863 }
2864
2865 Diag(Tok.getLocation(), diagnostic)
2866 << Ty
2867 << llvm::StringRef(buffer.data(), buffer.size());
2868 }
2869
2870 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002871 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002872
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002873 if (Ty == Context.DoubleTy) {
2874 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002875 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002876 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2877 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002878 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002879 }
2880 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002881 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002882 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002883 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002884 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002885
Neil Boothac582c52007-08-29 22:00:19 +00002886 // long long is a C99 feature.
2887 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002888 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002889 Diag(Tok.getLocation(), diag::ext_longlong);
2890
Chris Lattner67ca9252007-05-21 01:08:44 +00002891 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002892 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002893
Chris Lattner67ca9252007-05-21 01:08:44 +00002894 if (Literal.GetIntegerValue(ResultVal)) {
2895 // If this value didn't fit into uintmax_t, warn and force to ull.
2896 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002897 Ty = Context.UnsignedLongLongTy;
2898 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002899 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002900 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002901 // If this value fits into a ULL, try to figure out what else it fits into
2902 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002903
Chris Lattner67ca9252007-05-21 01:08:44 +00002904 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2905 // be an unsigned int.
2906 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2907
2908 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002909 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002910 if (!Literal.isLong && !Literal.isLongLong) {
2911 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002912 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002913
Chris Lattner67ca9252007-05-21 01:08:44 +00002914 // Does it fit in a unsigned int?
2915 if (ResultVal.isIntN(IntSize)) {
2916 // Does it fit in a signed int?
2917 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002918 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002919 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002920 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002921 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002922 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002923 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002924
Chris Lattner67ca9252007-05-21 01:08:44 +00002925 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002926 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002927 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002928
Chris Lattner67ca9252007-05-21 01:08:44 +00002929 // Does it fit in a unsigned long?
2930 if (ResultVal.isIntN(LongSize)) {
2931 // Does it fit in a signed long?
2932 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002933 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002934 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002935 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002936 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002937 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002938 }
2939
Chris Lattner67ca9252007-05-21 01:08:44 +00002940 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002941 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002942 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002943
Chris Lattner67ca9252007-05-21 01:08:44 +00002944 // Does it fit in a unsigned long long?
2945 if (ResultVal.isIntN(LongLongSize)) {
2946 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002947 // To be compatible with MSVC, hex integer literals ending with the
2948 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002949 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2950 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002951 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002952 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002953 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002954 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002955 }
2956 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002957
Chris Lattner67ca9252007-05-21 01:08:44 +00002958 // If we still couldn't decide a type, we probably have something that
2959 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002960 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002961 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002962 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002963 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002964 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002965
Chris Lattner55258cf2008-05-09 05:59:00 +00002966 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002967 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002968 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002969 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002970 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002971
Chris Lattner1c20a172007-08-26 03:42:43 +00002972 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2973 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002974 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002975 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002976
2977 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002978}
2979
John McCalldadc5752010-08-24 06:29:42 +00002980ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002981 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002982 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002983 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002984}
2985
Steve Naroff71b59a92007-06-04 22:22:31 +00002986/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00002987/// See C99 6.3.2.1p[2-4] for more details.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002988bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2989 SourceLocation OpLoc,
2990 SourceRange ExprRange,
2991 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002992 if (exprType->isDependentType())
2993 return false;
2994
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002995 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2996 // the result is the size of the referenced type."
2997 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2998 // result shall be the alignment of the referenced type."
2999 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
3000 exprType = Ref->getPointeeType();
3001
Peter Collingbournee190dee2011-03-11 19:24:49 +00003002 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3003 // scalar or vector data type argument..."
3004 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3005 // type (C99 6.2.5p18) or void.
3006 if (ExprKind == UETT_VecStep) {
3007 if (!(exprType->isArithmeticType() || exprType->isVoidType() ||
3008 exprType->isVectorType())) {
3009 Diag(OpLoc, diag::err_vecstep_non_scalar_vector_type)
3010 << exprType << ExprRange;
3011 return true;
3012 }
3013 }
3014
Steve Naroff043d45d2007-05-15 02:32:35 +00003015 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00003016 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00003017 // alignof(function) is allowed as an extension.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003018 if (ExprKind == UETT_SizeOf)
3019 Diag(OpLoc, diag::ext_sizeof_function_type)
3020 << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00003021 return false;
3022 }
Mike Stump11289f42009-09-09 15:08:12 +00003023
Peter Collingbournee190dee2011-03-11 19:24:49 +00003024 // Allow sizeof(void)/alignof(void) as an extension. vec_step(void) is not
3025 // an extension, as void is a built-in scalar type (OpenCL 1.1 6.1.1).
Chris Lattnerb1355b12009-01-24 19:46:37 +00003026 if (exprType->isVoidType()) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003027 if (ExprKind != UETT_VecStep)
3028 Diag(OpLoc, diag::ext_sizeof_void_type)
3029 << ExprKind << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00003030 return false;
3031 }
Mike Stump11289f42009-09-09 15:08:12 +00003032
Chris Lattner62975a72009-04-24 00:30:45 +00003033 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00003034 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00003035 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00003036 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003037
Chris Lattner62975a72009-04-24 00:30:45 +00003038 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00003039 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00003040 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Peter Collingbournee190dee2011-03-11 19:24:49 +00003041 << exprType << (ExprKind == UETT_SizeOf)
3042 << ExprRange;
Chris Lattnercd2a8c52009-04-24 22:30:50 +00003043 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00003044 }
Mike Stump11289f42009-09-09 15:08:12 +00003045
Chris Lattner62975a72009-04-24 00:30:45 +00003046 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00003047}
3048
John McCall36e7fe32010-10-12 00:20:44 +00003049static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
3050 SourceRange ExprRange) {
Chris Lattner8dff0172009-01-24 20:17:12 +00003051 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003052
Mike Stump11289f42009-09-09 15:08:12 +00003053 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00003054 if (isa<DeclRefExpr>(E))
3055 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003056
3057 // Cannot know anything else if the expression is dependent.
3058 if (E->isTypeDependent())
3059 return false;
3060
Douglas Gregor71235ec2009-05-02 02:18:30 +00003061 if (E->getBitField()) {
John McCall36e7fe32010-10-12 00:20:44 +00003062 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor71235ec2009-05-02 02:18:30 +00003063 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00003064 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003065
3066 // Alignment of a field access is always okay, so long as it isn't a
3067 // bit-field.
3068 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00003069 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003070 return false;
3071
Peter Collingbournee190dee2011-03-11 19:24:49 +00003072 return S.CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
3073 UETT_AlignOf);
3074}
3075
3076bool Sema::CheckVecStepExpr(Expr *E, SourceLocation OpLoc,
3077 SourceRange ExprRange) {
3078 E = E->IgnoreParens();
3079
3080 // Cannot know anything else if the expression is dependent.
3081 if (E->isTypeDependent())
3082 return false;
3083
3084 return CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
3085 UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00003086}
3087
Douglas Gregor0950e412009-03-13 21:01:28 +00003088/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00003089ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003090Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3091 SourceLocation OpLoc,
3092 UnaryExprOrTypeTrait ExprKind,
3093 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00003094 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00003095 return ExprError();
3096
John McCallbcd03502009-12-07 02:54:59 +00003097 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00003098
Douglas Gregor0950e412009-03-13 21:01:28 +00003099 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00003100 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00003101 return ExprError();
3102
3103 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003104 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3105 Context.getSizeType(),
3106 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003107}
3108
3109/// \brief Build a sizeof or alignof expression given an expression
3110/// operand.
John McCalldadc5752010-08-24 06:29:42 +00003111ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003112Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3113 UnaryExprOrTypeTrait ExprKind,
3114 SourceRange R) {
Douglas Gregor0950e412009-03-13 21:01:28 +00003115 // Verify that the operand is valid.
3116 bool isInvalid = false;
3117 if (E->isTypeDependent()) {
3118 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003119 } else if (ExprKind == UETT_AlignOf) {
John McCall36e7fe32010-10-12 00:20:44 +00003120 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003121 } else if (ExprKind == UETT_VecStep) {
3122 isInvalid = CheckVecStepExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00003123 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00003124 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
3125 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00003126 } else if (E->getType()->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00003127 ExprResult PE = CheckPlaceholderExpr(E);
John McCall36226622010-10-12 02:09:17 +00003128 if (PE.isInvalid()) return ExprError();
Peter Collingbournee190dee2011-03-11 19:24:49 +00003129 return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind, R);
Douglas Gregor0950e412009-03-13 21:01:28 +00003130 } else {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003131 isInvalid = CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, R,
3132 UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00003133 }
3134
3135 if (isInvalid)
3136 return ExprError();
3137
3138 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003139 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, E,
3140 Context.getSizeType(),
3141 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003142}
3143
Peter Collingbournee190dee2011-03-11 19:24:49 +00003144/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3145/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003146/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003147ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003148Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3149 UnaryExprOrTypeTrait ExprKind, bool isType,
3150 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003151 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003152 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003153
Sebastian Redl6f282892008-11-11 17:56:53 +00003154 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00003155 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003156 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003157 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003158 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003159
Douglas Gregor0950e412009-03-13 21:01:28 +00003160 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00003161 ExprResult Result
Peter Collingbournee190dee2011-03-11 19:24:49 +00003162 = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind,
3163 ArgEx->getSourceRange());
Douglas Gregor0950e412009-03-13 21:01:28 +00003164
Douglas Gregor0950e412009-03-13 21:01:28 +00003165 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00003166}
3167
John Wiegley01296292011-04-08 18:41:53 +00003168static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall4bc41ae2010-11-18 19:01:18 +00003169 bool isReal) {
John Wiegley01296292011-04-08 18:41:53 +00003170 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003171 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003172
John McCall34376a62010-12-04 03:47:34 +00003173 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003174 if (V.get()->getObjectKind() != OK_Ordinary) {
3175 V = S.DefaultLvalueConversion(V.take());
3176 if (V.isInvalid())
3177 return QualType();
3178 }
John McCall34376a62010-12-04 03:47:34 +00003179
Chris Lattnere267f5d2007-08-26 05:39:26 +00003180 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003181 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003182 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003183
Chris Lattnere267f5d2007-08-26 05:39:26 +00003184 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003185 if (V.get()->getType()->isArithmeticType())
3186 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003187
John McCall36226622010-10-12 02:09:17 +00003188 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003189 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003190 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003191 if (PR.get() != V.get()) {
3192 V = move(PR);
John McCall4bc41ae2010-11-18 19:01:18 +00003193 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00003194 }
3195
Chris Lattnere267f5d2007-08-26 05:39:26 +00003196 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003197 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00003198 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003199 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003200}
3201
3202
Chris Lattnere168f762006-11-10 05:29:30 +00003203
John McCalldadc5752010-08-24 06:29:42 +00003204ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003205Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003206 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003207 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003208 switch (Kind) {
3209 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003210 case tok::plusplus: Opc = UO_PostInc; break;
3211 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003212 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003213
John McCallb268a282010-08-23 23:25:46 +00003214 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003215}
3216
John McCall4bc41ae2010-11-18 19:01:18 +00003217/// Expressions of certain arbitrary types are forbidden by C from
3218/// having l-value type. These are:
3219/// - 'void', but not qualified void
3220/// - function types
3221///
3222/// The exact rule here is C99 6.3.2.1:
3223/// An lvalue is an expression with an object type or an incomplete
3224/// type other than void.
3225static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
3226 return ((T->isVoidType() && !T.hasQualifiers()) ||
3227 T->isFunctionType());
3228}
3229
John McCalldadc5752010-08-24 06:29:42 +00003230ExprResult
John McCallb268a282010-08-23 23:25:46 +00003231Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3232 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003233 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003234 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003235 if (Result.isInvalid()) return ExprError();
3236 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003237
John McCallb268a282010-08-23 23:25:46 +00003238 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003239
Douglas Gregor40412ac2008-11-19 17:17:41 +00003240 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003241 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003242 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003243 Context.DependentTy,
3244 VK_LValue, OK_Ordinary,
3245 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003246 }
3247
Mike Stump11289f42009-09-09 15:08:12 +00003248 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003249 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003250 LHSExp->getType()->isEnumeralType() ||
3251 RHSExp->getType()->isRecordType() ||
3252 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003253 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003254 }
3255
John McCallb268a282010-08-23 23:25:46 +00003256 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003257}
3258
3259
John McCalldadc5752010-08-24 06:29:42 +00003260ExprResult
John McCallb268a282010-08-23 23:25:46 +00003261Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3262 Expr *Idx, SourceLocation RLoc) {
3263 Expr *LHSExp = Base;
3264 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003265
Chris Lattner36d572b2007-07-16 00:14:47 +00003266 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003267 if (!LHSExp->getType()->getAs<VectorType>()) {
3268 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3269 if (Result.isInvalid())
3270 return ExprError();
3271 LHSExp = Result.take();
3272 }
3273 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3274 if (Result.isInvalid())
3275 return ExprError();
3276 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003277
Chris Lattner36d572b2007-07-16 00:14:47 +00003278 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003279 ExprValueKind VK = VK_LValue;
3280 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003281
Steve Naroffc1aadb12007-03-28 21:49:40 +00003282 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003283 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003284 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003285 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003286 Expr *BaseExpr, *IndexExpr;
3287 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003288 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3289 BaseExpr = LHSExp;
3290 IndexExpr = RHSExp;
3291 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003292 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003293 BaseExpr = LHSExp;
3294 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003295 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003296 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003297 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003298 BaseExpr = RHSExp;
3299 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003300 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003301 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003302 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003303 BaseExpr = LHSExp;
3304 IndexExpr = RHSExp;
3305 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003306 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003307 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003308 // Handle the uncommon case of "123[Ptr]".
3309 BaseExpr = RHSExp;
3310 IndexExpr = LHSExp;
3311 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003312 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003313 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003314 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003315 VK = LHSExp->getValueKind();
3316 if (VK != VK_RValue)
3317 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003318
Chris Lattner36d572b2007-07-16 00:14:47 +00003319 // FIXME: need to deal with const...
3320 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003321 } else if (LHSTy->isArrayType()) {
3322 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003323 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003324 // wasn't promoted because of the C90 rule that doesn't
3325 // allow promoting non-lvalue arrays. Warn, then
3326 // force the promotion here.
3327 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3328 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003329 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3330 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003331 LHSTy = LHSExp->getType();
3332
3333 BaseExpr = LHSExp;
3334 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003335 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003336 } else if (RHSTy->isArrayType()) {
3337 // Same as previous, except for 123[f().a] case
3338 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3339 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003340 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3341 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003342 RHSTy = RHSExp->getType();
3343
3344 BaseExpr = RHSExp;
3345 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003346 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003347 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003348 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3349 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003350 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003351 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003352 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003353 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3354 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003355
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003356 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003357 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3358 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003359 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3360
Douglas Gregorac1fb652009-03-24 19:52:54 +00003361 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003362 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3363 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003364 // incomplete types are not object types.
3365 if (ResultType->isFunctionType()) {
3366 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3367 << ResultType << BaseExpr->getSourceRange();
3368 return ExprError();
3369 }
Mike Stump11289f42009-09-09 15:08:12 +00003370
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003371 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3372 // GNU extension: subscripting on pointer to void
3373 Diag(LLoc, diag::ext_gnu_void_ptr)
3374 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003375
3376 // C forbids expressions of unqualified void type from being l-values.
3377 // See IsCForbiddenLValueType.
3378 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003379 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003380 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003381 PDiag(diag::err_subscript_incomplete_type)
3382 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003383 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003384
Chris Lattner62975a72009-04-24 00:30:45 +00003385 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003386 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003387 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3388 << ResultType << BaseExpr->getSourceRange();
3389 return ExprError();
3390 }
Mike Stump11289f42009-09-09 15:08:12 +00003391
John McCall4bc41ae2010-11-18 19:01:18 +00003392 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3393 !IsCForbiddenLValueType(Context, ResultType));
3394
Mike Stump4e1f26a2009-02-19 03:04:26 +00003395 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003396 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003397}
3398
John McCall4bc41ae2010-11-18 19:01:18 +00003399/// Check an ext-vector component access expression.
3400///
3401/// VK should be set in advance to the value kind of the base
3402/// expression.
3403static QualType
3404CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3405 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00003406 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00003407 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3408 // see FIXME there.
3409 //
3410 // FIXME: This logic can be greatly simplified by splitting it along
3411 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00003412 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00003413
Steve Narofff8fd09e2007-07-27 22:15:19 +00003414 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003415 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003416
Mike Stump4e1f26a2009-02-19 03:04:26 +00003417 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00003418 // special names that indicate a subset of exactly half the elements are
3419 // to be selected.
3420 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003421
Nate Begemanbb70bf62009-01-18 01:47:54 +00003422 // This flag determines whether or not CompName has an 's' char prefix,
3423 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00003424 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00003425
John McCall4bc41ae2010-11-18 19:01:18 +00003426 bool HasRepeated = false;
3427 bool HasIndex[16] = {};
3428
3429 int Idx;
3430
Nate Begemanf322eab2008-05-09 06:41:27 +00003431 // Check that we've found one of the special components, or that the component
3432 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003433 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00003434 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3435 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00003436 } else if (!HexSwizzle &&
3437 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3438 do {
3439 if (HasIndex[Idx]) HasRepeated = true;
3440 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003441 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003442 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3443 } else {
3444 if (HexSwizzle) compStr++;
3445 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3446 if (HasIndex[Idx]) HasRepeated = true;
3447 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003448 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003449 }
Chris Lattner7e152db2007-08-02 22:33:49 +00003450 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00003451
Mike Stump4e1f26a2009-02-19 03:04:26 +00003452 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00003453 // We didn't get to the end of the string. This means the component names
3454 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00003455 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003456 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00003457 return QualType();
3458 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003459
Nate Begemanbb70bf62009-01-18 01:47:54 +00003460 // Ensure no component accessor exceeds the width of the vector type it
3461 // operates on.
3462 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003463 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003464
3465 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00003466 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00003467
3468 while (*compStr) {
3469 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00003470 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00003471 << baseType << SourceRange(CompLoc);
3472 return QualType();
3473 }
3474 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00003475 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003476
Steve Narofff8fd09e2007-07-27 22:15:19 +00003477 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003478 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00003479 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00003480 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00003481 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00003482 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00003483 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003484 if (HexSwizzle)
3485 CompSize--;
3486
Steve Narofff8fd09e2007-07-27 22:15:19 +00003487 if (CompSize == 1)
3488 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003489
John McCall4bc41ae2010-11-18 19:01:18 +00003490 if (HasRepeated) VK = VK_RValue;
3491
3492 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003493 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00003494 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00003495 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3496 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3497 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00003498 }
3499 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00003500}
3501
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003502static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00003503 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003504 const Selector &Sel,
3505 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003506 if (Member)
3507 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3508 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003509 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003510 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003511
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003512 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3513 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003514 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3515 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003516 return D;
3517 }
3518 return 0;
3519}
3520
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003521static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3522 IdentifierInfo *Member,
3523 const Selector &Sel,
3524 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003525 // Check protocols on qualified interfaces.
3526 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003527 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003528 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003529 if (Member)
3530 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3531 GDecl = PD;
3532 break;
3533 }
3534 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003535 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003536 GDecl = OMD;
3537 break;
3538 }
3539 }
3540 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003541 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003542 E = QIdTy->qual_end(); I != E; ++I) {
3543 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003544 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3545 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003546 if (GDecl)
3547 return GDecl;
3548 }
3549 }
3550 return GDecl;
3551}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003552
John McCalldadc5752010-08-24 06:29:42 +00003553ExprResult
John McCallb268a282010-08-23 23:25:46 +00003554Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003555 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003556 const CXXScopeSpec &SS,
3557 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003558 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003559 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003560 // Even in dependent contexts, try to diagnose base expressions with
3561 // obviously wrong types, e.g.:
3562 //
3563 // T* t;
3564 // t.f;
3565 //
3566 // In Obj-C++, however, the above expression is valid, since it could be
3567 // accessing the 'f' property if T is an Obj-C interface. The extra check
3568 // allows this, while still reporting an error if T is a struct pointer.
3569 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003570 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003571 if (PT && (!getLangOptions().ObjC1 ||
3572 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003573 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003574 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003575 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003576 return ExprError();
3577 }
3578 }
3579
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003580 assert(BaseType->isDependentType() ||
3581 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003582 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003583
3584 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3585 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003586 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003587 IsArrow, OpLoc,
Douglas Gregore16af532011-02-28 18:50:33 +00003588 SS.getWithLocInContext(Context),
John McCall10eae182009-11-30 22:42:35 +00003589 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003590 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003591}
3592
3593/// We know that the given qualified member reference points only to
3594/// declarations which do not belong to the static type of the base
3595/// expression. Diagnose the problem.
3596static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3597 Expr *BaseExpr,
3598 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003599 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00003600 NamedDecl *rep,
3601 const DeclarationNameInfo &nameInfo) {
John McCallcd4b4772009-12-02 03:53:29 +00003602 // If this is an implicit member access, use a different set of
3603 // diagnostics.
3604 if (!BaseExpr)
John McCallf3a88602011-02-03 08:15:49 +00003605 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall10eae182009-11-30 22:42:35 +00003606
John McCallf3a88602011-02-03 08:15:49 +00003607 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3608 << SS.getRange() << rep << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003609}
3610
3611// Check whether the declarations we found through a nested-name
3612// specifier in a member expression are actually members of the base
3613// type. The restriction here is:
3614//
3615// C++ [expr.ref]p2:
3616// ... In these cases, the id-expression shall name a
3617// member of the class or of one of its base classes.
3618//
3619// So it's perfectly legitimate for the nested-name specifier to name
3620// an unrelated class, and for us to find an overload set including
3621// decls from classes which are not superclasses, as long as the decl
3622// we actually pick through overload resolution is from a superclass.
3623bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3624 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003625 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003626 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003627 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3628 if (!BaseRT) {
3629 // We can't check this yet because the base type is still
3630 // dependent.
3631 assert(BaseType->isDependentType());
3632 return false;
3633 }
3634 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003635
3636 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003637 // If this is an implicit member reference and we find a
3638 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003639 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003640 return false;
John McCall10eae182009-11-30 22:42:35 +00003641
John McCall2d74de92009-12-01 22:10:20 +00003642 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003643 DeclContext *DC = (*I)->getDeclContext();
3644 while (DC->isTransparentContext())
3645 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003646
Douglas Gregora9c3e822010-07-28 22:27:52 +00003647 if (!DC->isRecord())
3648 continue;
3649
John McCall2d74de92009-12-01 22:10:20 +00003650 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003651 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003652
3653 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3654 return false;
3655 }
3656
John McCallf3a88602011-02-03 08:15:49 +00003657 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3658 R.getRepresentativeDecl(),
3659 R.getLookupNameInfo());
John McCall2d74de92009-12-01 22:10:20 +00003660 return true;
3661}
3662
3663static bool
3664LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3665 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003666 SourceLocation OpLoc, CXXScopeSpec &SS,
3667 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003668 RecordDecl *RDecl = RTy->getDecl();
3669 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003670 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003671 << BaseRange))
3672 return true;
3673
John McCalle9cccd82010-06-16 08:42:20 +00003674 if (HasTemplateArgs) {
3675 // LookupTemplateName doesn't expect these both to exist simultaneously.
3676 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3677
3678 bool MOUS;
3679 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3680 return false;
3681 }
3682
John McCall2d74de92009-12-01 22:10:20 +00003683 DeclContext *DC = RDecl;
3684 if (SS.isSet()) {
3685 // If the member name was a qualified-id, look into the
3686 // nested-name-specifier.
3687 DC = SemaRef.computeDeclContext(SS, false);
3688
John McCall0b66eb32010-05-01 00:40:08 +00003689 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003690 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3691 << SS.getRange() << DC;
3692 return true;
3693 }
3694
John McCall2d74de92009-12-01 22:10:20 +00003695 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003696
John McCall2d74de92009-12-01 22:10:20 +00003697 if (!isa<TypeDecl>(DC)) {
3698 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3699 << DC << SS.getRange();
3700 return true;
John McCall10eae182009-11-30 22:42:35 +00003701 }
3702 }
3703
John McCall2d74de92009-12-01 22:10:20 +00003704 // The record definition is complete, now look up the member.
3705 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003706
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003707 if (!R.empty())
3708 return false;
3709
3710 // We didn't find anything with the given name, so try to correct
3711 // for typos.
3712 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003713 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003714 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003715 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3716 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3717 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003718 << FixItHint::CreateReplacement(R.getNameLoc(),
3719 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003720 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3721 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3722 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003723 return false;
3724 } else {
3725 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003726 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003727 }
3728
John McCall10eae182009-11-30 22:42:35 +00003729 return false;
3730}
3731
John McCalldadc5752010-08-24 06:29:42 +00003732ExprResult
John McCallb268a282010-08-23 23:25:46 +00003733Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003734 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003735 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003736 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003737 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003738 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003739 if (BaseType->isDependentType() ||
3740 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003741 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003742 IsArrow, OpLoc,
3743 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003744 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003745
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003746 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003747
John McCall2d74de92009-12-01 22:10:20 +00003748 // Implicit member accesses.
3749 if (!Base) {
3750 QualType RecordTy = BaseType;
3751 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3752 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3753 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003754 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003755 return ExprError();
3756
3757 // Explicit member accesses.
3758 } else {
John Wiegley01296292011-04-08 18:41:53 +00003759 ExprResult BaseResult = Owned(Base);
John McCalldadc5752010-08-24 06:29:42 +00003760 ExprResult Result =
John Wiegley01296292011-04-08 18:41:53 +00003761 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003762 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003763
John Wiegley01296292011-04-08 18:41:53 +00003764 if (BaseResult.isInvalid())
3765 return ExprError();
3766 Base = BaseResult.take();
3767
John McCall2d74de92009-12-01 22:10:20 +00003768 if (Result.isInvalid()) {
3769 Owned(Base);
3770 return ExprError();
3771 }
3772
3773 if (Result.get())
3774 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003775
3776 // LookupMemberExpr can modify Base, and thus change BaseType
3777 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003778 }
3779
John McCallb268a282010-08-23 23:25:46 +00003780 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003781 OpLoc, IsArrow, SS, FirstQualifierInScope,
3782 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003783}
3784
John McCalldadc5752010-08-24 06:29:42 +00003785ExprResult
John McCallb268a282010-08-23 23:25:46 +00003786Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003787 SourceLocation OpLoc, bool IsArrow,
3788 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003789 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003790 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003791 const TemplateArgumentListInfo *TemplateArgs,
3792 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003793 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003794 if (IsArrow) {
3795 assert(BaseType->isPointerType());
3796 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3797 }
John McCalla8ae2222010-04-06 21:38:20 +00003798 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003799
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003800 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3801 DeclarationName MemberName = MemberNameInfo.getName();
3802 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003803
3804 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003805 return ExprError();
3806
John McCall10eae182009-11-30 22:42:35 +00003807 if (R.empty()) {
3808 // Rederive where we looked up.
3809 DeclContext *DC = (SS.isSet()
3810 ? computeDeclContext(SS, false)
3811 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003812
John McCall10eae182009-11-30 22:42:35 +00003813 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003814 << MemberName << DC
3815 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003816 return ExprError();
3817 }
3818
John McCall38836f02010-01-15 08:34:02 +00003819 // Diagnose lookups that find only declarations from a non-base
3820 // type. This is possible for either qualified lookups (which may
3821 // have been qualified with an unrelated type) or implicit member
3822 // expressions (which were found with unqualified lookup and thus
3823 // may have come from an enclosing scope). Note that it's okay for
3824 // lookup to find declarations from a non-base type as long as those
3825 // aren't the ones picked by overload resolution.
3826 if ((SS.isSet() || !BaseExpr ||
3827 (isa<CXXThisExpr>(BaseExpr) &&
3828 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00003829 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00003830 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00003831 return ExprError();
3832
3833 // Construct an unresolved result if we in fact got an unresolved
3834 // result.
3835 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall58cc69d2010-01-27 01:50:18 +00003836 // Suppress any lookup-related diagnostics; we'll do these when we
3837 // pick a member.
3838 R.suppressDiagnostics();
3839
John McCall10eae182009-11-30 22:42:35 +00003840 UnresolvedMemberExpr *MemExpr
Douglas Gregora6e053e2010-12-15 01:34:56 +00003841 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00003842 BaseExpr, BaseExprType,
3843 IsArrow, OpLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003844 SS.getWithLocInContext(Context),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003845 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003846 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00003847
3848 return Owned(MemExpr);
3849 }
3850
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003851 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00003852 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00003853 NamedDecl *MemberDecl = R.getFoundDecl();
3854
3855 // FIXME: diagnose the presence of template arguments now.
3856
3857 // If the decl being referenced had an error, return an error for this
3858 // sub-expr without emitting another error, in order to avoid cascading
3859 // error cases.
3860 if (MemberDecl->isInvalidDecl())
3861 return ExprError();
3862
John McCall2d74de92009-12-01 22:10:20 +00003863 // Handle the implicit-member-access case.
3864 if (!BaseExpr) {
3865 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00003866 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003867 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00003868
Douglas Gregorb15af892010-01-07 23:12:05 +00003869 SourceLocation Loc = R.getNameLoc();
3870 if (SS.getRange().isValid())
3871 Loc = SS.getRange().getBegin();
3872 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003873 }
3874
John McCall10eae182009-11-30 22:42:35 +00003875 bool ShouldCheckUse = true;
3876 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3877 // Don't diagnose the use of a virtual member function unless it's
3878 // explicitly qualified.
3879 if (MD->isVirtual() && !SS.isSet())
3880 ShouldCheckUse = false;
3881 }
3882
3883 // Check the use of this member.
3884 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3885 Owned(BaseExpr);
3886 return ExprError();
3887 }
3888
John McCall34376a62010-12-04 03:47:34 +00003889 // Perform a property load on the base regardless of whether we
3890 // actually need it for the declaration.
John Wiegley01296292011-04-08 18:41:53 +00003891 if (BaseExpr->getObjectKind() == OK_ObjCProperty) {
3892 ExprResult Result = ConvertPropertyForRValue(BaseExpr);
3893 if (Result.isInvalid())
3894 return ExprError();
3895 BaseExpr = Result.take();
3896 }
John McCall34376a62010-12-04 03:47:34 +00003897
John McCallfeb624a2010-11-23 20:48:44 +00003898 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3899 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3900 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00003901
Francois Pichet783dd6e2010-11-21 06:08:52 +00003902 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3903 // We may have found a field within an anonymous union or struct
3904 // (C++ [class.union]).
John McCallf3a88602011-02-03 08:15:49 +00003905 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCall34376a62010-12-04 03:47:34 +00003906 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003907
John McCall10eae182009-11-30 22:42:35 +00003908 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3909 MarkDeclarationReferenced(MemberLoc, Var);
3910 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003911 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003912 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00003913 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003914 }
3915
John McCall7decc9e2010-11-18 06:31:45 +00003916 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall10eae182009-11-30 22:42:35 +00003917 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3918 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003919 MemberFn, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003920 MemberFn->getType(),
3921 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3922 OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003923 }
John McCall7decc9e2010-11-18 06:31:45 +00003924 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00003925
3926 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3927 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3928 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003929 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003930 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003931 }
3932
3933 Owned(BaseExpr);
3934
Douglas Gregor861eb802010-04-25 20:55:08 +00003935 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00003936 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003937 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00003938 << MemberName << BaseType << int(IsArrow);
3939 else
3940 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3941 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00003942
Douglas Gregor861eb802010-04-25 20:55:08 +00003943 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3944 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00003945 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00003946 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003947}
3948
John McCall68fc88ec2010-12-15 16:46:44 +00003949/// Given that normal member access failed on the given expression,
3950/// and given that the expression's type involves builtin-id or
3951/// builtin-Class, decide whether substituting in the redefinition
3952/// types would be profitable. The redefinition type is whatever
3953/// this translation unit tried to typedef to id/Class; we store
3954/// it to the side and then re-use it in places like this.
John Wiegley01296292011-04-08 18:41:53 +00003955static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
John McCall68fc88ec2010-12-15 16:46:44 +00003956 const ObjCObjectPointerType *opty
John Wiegley01296292011-04-08 18:41:53 +00003957 = base.get()->getType()->getAs<ObjCObjectPointerType>();
John McCall68fc88ec2010-12-15 16:46:44 +00003958 if (!opty) return false;
3959
3960 const ObjCObjectType *ty = opty->getObjectType();
3961
3962 QualType redef;
3963 if (ty->isObjCId()) {
3964 redef = S.Context.ObjCIdRedefinitionType;
3965 } else if (ty->isObjCClass()) {
3966 redef = S.Context.ObjCClassRedefinitionType;
3967 } else {
3968 return false;
3969 }
3970
3971 // Do the substitution as long as the redefinition type isn't just a
3972 // possibly-qualified pointer to builtin-id or builtin-Class again.
3973 opty = redef->getAs<ObjCObjectPointerType>();
3974 if (opty && !opty->getObjectType()->getInterface() != 0)
3975 return false;
3976
John Wiegley01296292011-04-08 18:41:53 +00003977 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
John McCall68fc88ec2010-12-15 16:46:44 +00003978 return true;
3979}
3980
John McCall10eae182009-11-30 22:42:35 +00003981/// Look up the given member of the given non-type-dependent
3982/// expression. This can return in one of two ways:
3983/// * If it returns a sentinel null-but-valid result, the caller will
3984/// assume that lookup was performed and the results written into
3985/// the provided structure. It will take over from there.
3986/// * Otherwise, the returned expression will be produced in place of
3987/// an ordinary member expression.
3988///
3989/// The ObjCImpDecl bit is a gross hack that will need to be properly
3990/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00003991ExprResult
John Wiegley01296292011-04-08 18:41:53 +00003992Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00003993 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003994 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00003995 Decl *ObjCImpDecl, bool HasTemplateArgs) {
John Wiegley01296292011-04-08 18:41:53 +00003996 assert(BaseExpr.get() && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00003997
Steve Naroffeaaae462007-12-16 21:42:28 +00003998 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003999 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004000
John Wiegley01296292011-04-08 18:41:53 +00004001 if (IsArrow) {
4002 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4003 if (BaseExpr.isInvalid())
4004 return ExprError();
4005 }
4006
4007 QualType BaseType = BaseExpr.get()->getType();
John McCall10eae182009-11-30 22:42:35 +00004008 assert(!BaseType->isDependentType());
4009
4010 DeclarationName MemberName = R.getLookupName();
4011 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00004012
John McCall68fc88ec2010-12-15 16:46:44 +00004013 // For later type-checking purposes, turn arrow accesses into dot
4014 // accesses. The only access type we support that doesn't follow
4015 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
4016 // and those never use arrows, so this is unaffected.
4017 if (IsArrow) {
4018 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4019 BaseType = Ptr->getPointeeType();
4020 else if (const ObjCObjectPointerType *Ptr
4021 = BaseType->getAs<ObjCObjectPointerType>())
4022 BaseType = Ptr->getPointeeType();
4023 else if (BaseType->isRecordType()) {
4024 // Recover from arrow accesses to records, e.g.:
4025 // struct MyRecord foo;
4026 // foo->bar
4027 // This is actually well-formed in C++ if MyRecord has an
4028 // overloaded operator->, but that should have been dealt with
4029 // by now.
4030 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley01296292011-04-08 18:41:53 +00004031 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
John McCall68fc88ec2010-12-15 16:46:44 +00004032 << FixItHint::CreateReplacement(OpLoc, ".");
4033 IsArrow = false;
4034 } else {
4035 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
John Wiegley01296292011-04-08 18:41:53 +00004036 << BaseType << BaseExpr.get()->getSourceRange();
John McCall68fc88ec2010-12-15 16:46:44 +00004037 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00004038 }
4039 }
4040
John McCall68fc88ec2010-12-15 16:46:44 +00004041 // Handle field access to simple records.
4042 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John Wiegley01296292011-04-08 18:41:53 +00004043 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
John McCall68fc88ec2010-12-15 16:46:44 +00004044 RTy, OpLoc, SS, HasTemplateArgs))
4045 return ExprError();
4046
4047 // Returning valid-but-null is how we indicate to the caller that
4048 // the lookup result was filled in.
4049 return Owned((Expr*) 0);
David Chisnall9f57c292009-08-17 16:35:33 +00004050 }
John McCall10eae182009-11-30 22:42:35 +00004051
John McCall68fc88ec2010-12-15 16:46:44 +00004052 // Handle ivar access to Objective-C objects.
4053 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004054 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall68fc88ec2010-12-15 16:46:44 +00004055
4056 // There are three cases for the base type:
4057 // - builtin id (qualified or unqualified)
4058 // - builtin Class (qualified or unqualified)
4059 // - an interface
4060 ObjCInterfaceDecl *IDecl = OTy->getInterface();
4061 if (!IDecl) {
4062 // There's an implicit 'isa' ivar on all objects.
4063 // But we only actually find it this way on objects of type 'id',
4064 // apparently.
4065 if (OTy->isObjCId() && Member->isStr("isa"))
John Wiegley01296292011-04-08 18:41:53 +00004066 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
John McCall68fc88ec2010-12-15 16:46:44 +00004067 Context.getObjCClassType()));
4068
4069 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4070 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4071 ObjCImpDecl, HasTemplateArgs);
4072 goto fail;
4073 }
4074
4075 ObjCInterfaceDecl *ClassDeclared;
4076 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
4077
4078 if (!IV) {
4079 // Attempt to correct for typos in ivar names.
4080 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
4081 LookupMemberName);
4082 if (CorrectTypo(Res, 0, 0, IDecl, false,
4083 IsArrow ? CTC_ObjCIvarLookup
4084 : CTC_ObjCPropertyLookup) &&
4085 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
4086 Diag(R.getNameLoc(),
4087 diag::err_typecheck_member_reference_ivar_suggest)
4088 << IDecl->getDeclName() << MemberName << IV->getDeclName()
4089 << FixItHint::CreateReplacement(R.getNameLoc(),
4090 IV->getNameAsString());
4091 Diag(IV->getLocation(), diag::note_previous_decl)
4092 << IV->getDeclName();
4093 } else {
4094 Res.clear();
4095 Res.setLookupName(Member);
4096
4097 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
4098 << IDecl->getDeclName() << MemberName
John Wiegley01296292011-04-08 18:41:53 +00004099 << BaseExpr.get()->getSourceRange();
John McCall68fc88ec2010-12-15 16:46:44 +00004100 return ExprError();
4101 }
4102 }
4103
4104 // If the decl being referenced had an error, return an error for this
4105 // sub-expr without emitting another error, in order to avoid cascading
4106 // error cases.
4107 if (IV->isInvalidDecl())
4108 return ExprError();
4109
4110 // Check whether we can reference this field.
4111 if (DiagnoseUseOfDecl(IV, MemberLoc))
4112 return ExprError();
4113 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
4114 IV->getAccessControl() != ObjCIvarDecl::Package) {
4115 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
4116 if (ObjCMethodDecl *MD = getCurMethodDecl())
4117 ClassOfMethodDecl = MD->getClassInterface();
4118 else if (ObjCImpDecl && getCurFunctionDecl()) {
4119 // Case of a c-function declared inside an objc implementation.
4120 // FIXME: For a c-style function nested inside an objc implementation
4121 // class, there is no implementation context available, so we pass
4122 // down the context as argument to this routine. Ideally, this context
4123 // need be passed down in the AST node and somehow calculated from the
4124 // AST for a function decl.
4125 if (ObjCImplementationDecl *IMPD =
4126 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
4127 ClassOfMethodDecl = IMPD->getClassInterface();
4128 else if (ObjCCategoryImplDecl* CatImplClass =
4129 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
4130 ClassOfMethodDecl = CatImplClass->getClassInterface();
4131 }
4132
4133 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
4134 if (ClassDeclared != IDecl ||
4135 ClassOfMethodDecl != ClassDeclared)
4136 Diag(MemberLoc, diag::error_private_ivar_access)
4137 << IV->getDeclName();
4138 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
4139 // @protected
4140 Diag(MemberLoc, diag::error_protected_ivar_access)
4141 << IV->getDeclName();
4142 }
4143
4144 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
John Wiegley01296292011-04-08 18:41:53 +00004145 MemberLoc, BaseExpr.take(),
John McCall68fc88ec2010-12-15 16:46:44 +00004146 IsArrow));
4147 }
4148
4149 // Objective-C property access.
4150 const ObjCObjectPointerType *OPT;
4151 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
4152 // This actually uses the base as an r-value.
John Wiegley01296292011-04-08 18:41:53 +00004153 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4154 if (BaseExpr.isInvalid())
4155 return ExprError();
4156
4157 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
John McCall68fc88ec2010-12-15 16:46:44 +00004158
4159 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
4160
4161 const ObjCObjectType *OT = OPT->getObjectType();
4162
4163 // id, with and without qualifiers.
4164 if (OT->isObjCId()) {
4165 // Check protocols on qualified interfaces.
4166 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
4167 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
4168 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
4169 // Check the use of this declaration
4170 if (DiagnoseUseOfDecl(PD, MemberLoc))
4171 return ExprError();
4172
4173 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
4174 VK_LValue,
4175 OK_ObjCProperty,
4176 MemberLoc,
John Wiegley01296292011-04-08 18:41:53 +00004177 BaseExpr.take()));
John McCall68fc88ec2010-12-15 16:46:44 +00004178 }
4179
4180 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
4181 // Check the use of this method.
4182 if (DiagnoseUseOfDecl(OMD, MemberLoc))
4183 return ExprError();
4184 Selector SetterSel =
4185 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4186 PP.getSelectorTable(), Member);
4187 ObjCMethodDecl *SMD = 0;
4188 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
4189 SetterSel, Context))
4190 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
4191 QualType PType = OMD->getSendResultType();
4192
4193 ExprValueKind VK = VK_LValue;
4194 if (!getLangOptions().CPlusPlus &&
4195 IsCForbiddenLValueType(Context, PType))
4196 VK = VK_RValue;
4197 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4198
4199 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
4200 VK, OK,
John Wiegley01296292011-04-08 18:41:53 +00004201 MemberLoc, BaseExpr.take()));
John McCall68fc88ec2010-12-15 16:46:44 +00004202 }
4203 }
Fariborz Jahanianb03a4c22011-03-15 17:27:48 +00004204 // Use of id.member can only be for a property reference. Do not
4205 // use the 'id' redefinition in this case.
4206 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
John McCall68fc88ec2010-12-15 16:46:44 +00004207 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4208 ObjCImpDecl, HasTemplateArgs);
4209
4210 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
4211 << MemberName << BaseType);
4212 }
4213
4214 // 'Class', unqualified only.
4215 if (OT->isObjCClass()) {
4216 // Only works in a method declaration (??!).
4217 ObjCMethodDecl *MD = getCurMethodDecl();
4218 if (!MD) {
4219 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4220 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4221 ObjCImpDecl, HasTemplateArgs);
4222
4223 goto fail;
4224 }
4225
4226 // Also must look for a getter name which uses property syntax.
4227 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004228 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4229 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004230 if ((Getter = IFace->lookupClassMethod(Sel))) {
4231 // Check the use of this method.
4232 if (DiagnoseUseOfDecl(Getter, MemberLoc))
4233 return ExprError();
John McCall68fc88ec2010-12-15 16:46:44 +00004234 } else
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00004235 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004236 // If we found a getter then this may be a valid dot-reference, we
4237 // will look for the matching setter, in case it is needed.
4238 Selector SetterSel =
John McCall68fc88ec2010-12-15 16:46:44 +00004239 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4240 PP.getSelectorTable(), Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004241 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
4242 if (!Setter) {
4243 // If this reference is in an @implementation, also check for 'private'
4244 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00004245 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004246 }
4247 // Look through local category implementations associated with the class.
4248 if (!Setter)
4249 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004250
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004251 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
4252 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004253
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004254 if (Getter || Setter) {
4255 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004256
John McCall4bc41ae2010-11-18 19:01:18 +00004257 ExprValueKind VK = VK_LValue;
4258 if (Getter) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004259 PType = Getter->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00004260 if (!getLangOptions().CPlusPlus &&
4261 IsCForbiddenLValueType(Context, PType))
4262 VK = VK_RValue;
4263 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004264 // Get the expression type from Setter's incoming parameter.
4265 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00004266 }
4267 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4268
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004269 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00004270 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
4271 PType, VK, OK,
John Wiegley01296292011-04-08 18:41:53 +00004272 MemberLoc, BaseExpr.take()));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004273 }
John McCall68fc88ec2010-12-15 16:46:44 +00004274
4275 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4276 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4277 ObjCImpDecl, HasTemplateArgs);
4278
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004279 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall68fc88ec2010-12-15 16:46:44 +00004280 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004281 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004282
John McCall68fc88ec2010-12-15 16:46:44 +00004283 // Normal property access.
John Wiegley01296292011-04-08 18:41:53 +00004284 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), MemberName, MemberLoc,
John McCall68fc88ec2010-12-15 16:46:44 +00004285 SourceLocation(), QualType(), false);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004286 }
Alexis Huntc46382e2010-04-28 23:02:27 +00004287
Chris Lattnerb63a7452008-07-21 04:28:12 +00004288 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00004289 if (BaseType->isExtVectorType()) {
John McCall15317a22010-12-15 04:42:30 +00004290 // FIXME: this expr should store IsArrow.
Anders Carlssonf571c112009-08-26 18:25:21 +00004291 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John Wiegley01296292011-04-08 18:41:53 +00004292 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
John McCall4bc41ae2010-11-18 19:01:18 +00004293 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
4294 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00004295 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004296 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00004297
John Wiegley01296292011-04-08 18:41:53 +00004298 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
John McCall4bc41ae2010-11-18 19:01:18 +00004299 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00004300 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004301
John McCall68fc88ec2010-12-15 16:46:44 +00004302 // Adjust builtin-sel to the appropriate redefinition type if that's
4303 // not just a pointer to builtin-sel again.
4304 if (IsArrow &&
4305 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4306 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
John Wiegley01296292011-04-08 18:41:53 +00004307 BaseExpr = ImpCastExprToType(BaseExpr.take(), Context.ObjCSelRedefinitionType,
4308 CK_BitCast);
John McCall68fc88ec2010-12-15 16:46:44 +00004309 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4310 ObjCImpDecl, HasTemplateArgs);
4311 }
4312
4313 // Failure cases.
4314 fail:
4315
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004316 // Recover from dot accesses to pointers, e.g.:
4317 // type *foo;
4318 // foo.bar
4319 // This is actually well-formed in two cases:
4320 // - 'type' is an Objective C type
4321 // - 'bar' is a pseudo-destructor name which happens to refer to
4322 // the appropriate pointer type
John McCall68fc88ec2010-12-15 16:46:44 +00004323 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004324 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4325 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall68fc88ec2010-12-15 16:46:44 +00004326 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley01296292011-04-08 18:41:53 +00004327 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004328 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall68fc88ec2010-12-15 16:46:44 +00004329
4330 // Recurse as an -> access.
4331 IsArrow = true;
4332 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4333 ObjCImpDecl, HasTemplateArgs);
4334 }
John McCall68fc88ec2010-12-15 16:46:44 +00004335 }
4336
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004337 // If the user is trying to apply -> or . to a function name, it's probably
4338 // because they forgot parentheses to call that function.
4339 bool TryCall = false;
4340 bool Overloaded = false;
4341 UnresolvedSet<8> AllOverloads;
John Wiegley01296292011-04-08 18:41:53 +00004342 if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(BaseExpr.get())) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004343 AllOverloads.append(Overloads->decls_begin(), Overloads->decls_end());
4344 TryCall = true;
4345 Overloaded = true;
John Wiegley01296292011-04-08 18:41:53 +00004346 } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(BaseExpr.get())) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004347 if (FunctionDecl* Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
4348 AllOverloads.addDecl(Fun);
4349 TryCall = true;
4350 }
4351 }
John McCall68fc88ec2010-12-15 16:46:44 +00004352
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004353 if (TryCall) {
4354 // Plunder the overload set for something that would make the member
4355 // expression valid.
4356 UnresolvedSet<4> ViableOverloads;
4357 bool HasViableZeroArgOverload = false;
4358 for (OverloadExpr::decls_iterator it = AllOverloads.begin(),
4359 DeclsEnd = AllOverloads.end(); it != DeclsEnd; ++it) {
Matt Beaumont-Gayf8bb45f2011-03-05 02:42:30 +00004360 // Our overload set may include TemplateDecls, which we'll ignore for the
4361 // purposes of determining whether we can issue a '()' fixit.
4362 if (const FunctionDecl *OverloadDecl = dyn_cast<FunctionDecl>(*it)) {
4363 QualType ResultTy = OverloadDecl->getResultType();
4364 if ((!IsArrow && ResultTy->isRecordType()) ||
4365 (IsArrow && ResultTy->isPointerType() &&
4366 ResultTy->getPointeeType()->isRecordType())) {
4367 ViableOverloads.addDecl(*it);
4368 if (OverloadDecl->getMinRequiredArguments() == 0) {
4369 HasViableZeroArgOverload = true;
4370 }
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004371 }
John McCall68fc88ec2010-12-15 16:46:44 +00004372 }
4373 }
4374
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004375 if (!HasViableZeroArgOverload || ViableOverloads.size() != 1) {
John Wiegley01296292011-04-08 18:41:53 +00004376 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gayf8bb45f2011-03-05 02:42:30 +00004377 << (AllOverloads.size() > 1) << 0
John Wiegley01296292011-04-08 18:41:53 +00004378 << BaseExpr.get()->getSourceRange();
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004379 int ViableOverloadCount = ViableOverloads.size();
4380 int I;
4381 for (I = 0; I < ViableOverloadCount; ++I) {
4382 // FIXME: Magic number for max shown overloads stolen from
4383 // OverloadCandidateSet::NoteCandidates.
4384 if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
4385 break;
4386 }
4387 Diag(ViableOverloads[I].getDecl()->getSourceRange().getBegin(),
4388 diag::note_member_ref_possible_intended_overload);
4389 }
4390 if (I != ViableOverloadCount) {
John Wiegley01296292011-04-08 18:41:53 +00004391 Diag(BaseExpr.get()->getExprLoc(), diag::note_ovl_too_many_candidates)
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004392 << int(ViableOverloadCount - I);
4393 }
4394 return ExprError();
4395 }
4396 } else {
4397 // We don't have an expression that's convenient to get a Decl from, but we
4398 // can at least check if the type is "function of 0 arguments which returns
4399 // an acceptable type".
4400 const FunctionType *Fun = NULL;
4401 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4402 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4403 TryCall = true;
4404 }
4405 } else if ((Fun = BaseType->getAs<FunctionType>())) {
4406 TryCall = true;
4407 }
John McCall68fc88ec2010-12-15 16:46:44 +00004408
4409 if (TryCall) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004410 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4411 if (FPT->getNumArgs() == 0) {
4412 QualType ResultTy = Fun->getResultType();
4413 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4414 (IsArrow && ResultTy->isPointerType() &&
4415 ResultTy->getPointeeType()->isRecordType());
4416 }
Matt Beaumont-Gay956fc1c2011-02-17 02:54:17 +00004417 }
John McCall68fc88ec2010-12-15 16:46:44 +00004418 }
4419 }
4420
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004421 if (TryCall) {
4422 // At this point, we know BaseExpr looks like it's potentially callable with
4423 // 0 arguments, and that it returns something of a reasonable type, so we
4424 // can emit a fixit and carry on pretending that BaseExpr was actually a
4425 // CallExpr.
4426 SourceLocation ParenInsertionLoc =
John Wiegley01296292011-04-08 18:41:53 +00004427 PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
4428 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004429 << int(Overloaded) << 1
John Wiegley01296292011-04-08 18:41:53 +00004430 << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004431 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
John Wiegley01296292011-04-08 18:41:53 +00004432 ExprResult NewBase = ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004433 MultiExprArg(*this, 0, 0),
4434 ParenInsertionLoc);
4435 if (NewBase.isInvalid())
4436 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004437 BaseExpr = NewBase;
4438 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004439 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4440 ObjCImpDecl, HasTemplateArgs);
4441 }
4442
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004443 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
John Wiegley01296292011-04-08 18:41:53 +00004444 << BaseType << BaseExpr.get()->getSourceRange();
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004445
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004446 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00004447}
4448
John McCall10eae182009-11-30 22:42:35 +00004449/// The main callback when the parser finds something like
4450/// expression . [nested-name-specifier] identifier
4451/// expression -> [nested-name-specifier] identifier
4452/// where 'identifier' encompasses a fairly broad spectrum of
4453/// possibilities, including destructor and operator references.
4454///
4455/// \param OpKind either tok::arrow or tok::period
4456/// \param HasTrailingLParen whether the next token is '(', which
4457/// is used to diagnose mis-uses of special members that can
4458/// only be called
4459/// \param ObjCImpDecl the current ObjC @implementation decl;
4460/// this is an ugly hack around the fact that ObjC @implementations
4461/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00004462ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall15317a22010-12-15 04:42:30 +00004463 SourceLocation OpLoc,
4464 tok::TokenKind OpKind,
4465 CXXScopeSpec &SS,
4466 UnqualifiedId &Id,
4467 Decl *ObjCImpDecl,
4468 bool HasTrailingLParen) {
John McCall10eae182009-11-30 22:42:35 +00004469 if (SS.isSet() && SS.isInvalid())
4470 return ExprError();
4471
Francois Pichet64225792011-01-18 05:04:39 +00004472 // Warn about the explicit constructor calls Microsoft extension.
4473 if (getLangOptions().Microsoft &&
4474 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4475 Diag(Id.getSourceRange().getBegin(),
4476 diag::ext_ms_explicit_constructor_call);
4477
John McCall10eae182009-11-30 22:42:35 +00004478 TemplateArgumentListInfo TemplateArgsBuffer;
4479
4480 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004481 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00004482 const TemplateArgumentListInfo *TemplateArgs;
4483 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004484 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004485
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004486 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00004487 bool IsArrow = (OpKind == tok::arrow);
4488
4489 NamedDecl *FirstQualifierInScope
4490 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4491 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4492
4493 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004494 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004495 if (Result.isInvalid()) return ExprError();
4496 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00004497
Douglas Gregor41f90302010-04-12 20:54:26 +00004498 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4499 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00004500 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00004501 IsArrow, OpLoc,
4502 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004503 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004504 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004505 LookupResult R(*this, NameInfo, LookupMemberName);
John Wiegley01296292011-04-08 18:41:53 +00004506 ExprResult BaseResult = Owned(Base);
4507 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCalle9cccd82010-06-16 08:42:20 +00004508 SS, ObjCImpDecl, TemplateArgs != 0);
John Wiegley01296292011-04-08 18:41:53 +00004509 if (BaseResult.isInvalid())
4510 return ExprError();
4511 Base = BaseResult.take();
Alexis Huntc46382e2010-04-28 23:02:27 +00004512
John McCalle9cccd82010-06-16 08:42:20 +00004513 if (Result.isInvalid()) {
4514 Owned(Base);
4515 return ExprError();
4516 }
John McCall10eae182009-11-30 22:42:35 +00004517
John McCalle9cccd82010-06-16 08:42:20 +00004518 if (Result.get()) {
4519 // The only way a reference to a destructor can be used is to
4520 // immediately call it, which falls into this case. If the
4521 // next token is not a '(', produce a diagnostic and build the
4522 // call now.
4523 if (!HasTrailingLParen &&
4524 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00004525 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00004526
John McCalle9cccd82010-06-16 08:42:20 +00004527 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00004528 }
4529
John McCallb268a282010-08-23 23:25:46 +00004530 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00004531 OpLoc, IsArrow, SS, FirstQualifierInScope,
4532 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004533 }
4534
4535 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00004536}
4537
John McCalldadc5752010-08-24 06:29:42 +00004538ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00004539 FunctionDecl *FD,
4540 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00004541 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004542 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00004543 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00004544 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004545 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00004546 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004547 return ExprError();
4548 }
4549
4550 if (Param->hasUninstantiatedDefaultArg()) {
4551 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00004552
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004553 // Instantiate the expression.
4554 MultiLevelTemplateArgumentList ArgList
4555 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00004556
Nico Weber44887f62010-11-29 18:19:25 +00004557 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004558 = ArgList.getInnermost();
4559 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4560 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00004561
Nico Weber44887f62010-11-29 18:19:25 +00004562 ExprResult Result;
4563 {
4564 // C++ [dcl.fct.default]p5:
4565 // The names in the [default argument] expression are bound, and
4566 // the semantic constraints are checked, at the point where the
4567 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00004568 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00004569 Result = SubstExpr(UninstExpr, ArgList);
4570 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004571 if (Result.isInvalid())
4572 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004573
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004574 // Check the expression as an initializer for the parameter.
4575 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004576 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004577 InitializationKind Kind
4578 = InitializationKind::CreateCopy(Param->getLocation(),
4579 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4580 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004581
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004582 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4583 Result = InitSeq.Perform(*this, Entity, Kind,
4584 MultiExprArg(*this, &ResultE, 1));
4585 if (Result.isInvalid())
4586 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004587
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004588 // Build the default argument expression.
4589 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4590 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00004591 }
4592
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004593 // If the default expression creates temporaries, we need to
4594 // push them to the current stack of expression temporaries so they'll
4595 // be properly destroyed.
4596 // FIXME: We should really be rebuilding the default argument with new
4597 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004598 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4599 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4600 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4601 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4602 ExprTemporaries.push_back(Temporary);
4603 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004604
4605 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004606 // Just mark all of the declarations in this potentially-evaluated expression
4607 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004608 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00004609 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00004610}
4611
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004612/// ConvertArgumentsForCall - Converts the arguments specified in
4613/// Args/NumArgs to the parameter types of the function FDecl with
4614/// function prototype Proto. Call is the call expression itself, and
4615/// Fn is the function expression. For a C++ member function, this
4616/// routine does not attempt to convert the object argument. Returns
4617/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004618bool
4619Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004620 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004621 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004622 Expr **Args, unsigned NumArgs,
4623 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00004624 // Bail out early if calling a builtin with custom typechecking.
4625 // We don't need to do this in the
4626 if (FDecl)
4627 if (unsigned ID = FDecl->getBuiltinID())
4628 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4629 return false;
4630
Mike Stump4e1f26a2009-02-19 03:04:26 +00004631 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004632 // assignment, to the types of the corresponding parameter, ...
4633 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004634 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004635
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004636 // If too few arguments are available (and we don't have default
4637 // arguments for the remaining parameters), don't make the call.
4638 if (NumArgs < NumArgsInProto) {
4639 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4640 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004641 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00004642 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00004643 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004644 }
4645
4646 // If too many are passed and not variadic, error on the extras and drop
4647 // them.
4648 if (NumArgs > NumArgsInProto) {
4649 if (!Proto->isVariadic()) {
4650 Diag(Args[NumArgsInProto]->getLocStart(),
4651 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004652 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004653 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004654 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4655 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00004656
4657 // Emit the location of the prototype.
4658 if (FDecl && !FDecl->getBuiltinID())
4659 Diag(FDecl->getLocStart(),
4660 diag::note_typecheck_call_too_many_args)
4661 << FDecl;
4662
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004663 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004664 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004665 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004666 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004667 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004668 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004669 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004670 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4671 if (Fn->getType()->isBlockPointerType())
4672 CallType = VariadicBlock; // Block
4673 else if (isa<MemberExpr>(Fn))
4674 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004675 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004676 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004677 if (Invalid)
4678 return true;
4679 unsigned TotalNumArgs = AllArgs.size();
4680 for (unsigned i = 0; i < TotalNumArgs; ++i)
4681 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004682
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004683 return false;
4684}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004685
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004686bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4687 FunctionDecl *FDecl,
4688 const FunctionProtoType *Proto,
4689 unsigned FirstProtoArg,
4690 Expr **Args, unsigned NumArgs,
4691 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004692 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004693 unsigned NumArgsInProto = Proto->getNumArgs();
4694 unsigned NumArgsToCheck = NumArgs;
4695 bool Invalid = false;
4696 if (NumArgs != NumArgsInProto)
4697 // Use default arguments for missing arguments
4698 NumArgsToCheck = NumArgsInProto;
4699 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004700 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004701 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004702 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004703
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004704 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004705 if (ArgIx < NumArgs) {
4706 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004707
Eli Friedman3164fb12009-03-22 22:00:50 +00004708 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4709 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004710 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004711 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004712 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004713
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004714 // Pass the argument
4715 ParmVarDecl *Param = 0;
4716 if (FDecl && i < FDecl->getNumParams())
4717 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004718
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004719 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004720 Param? InitializedEntity::InitializeParameter(Context, Param)
4721 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00004722 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004723 SourceLocation(),
4724 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004725 if (ArgE.isInvalid())
4726 return true;
4727
4728 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004729 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004730 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004731
John McCalldadc5752010-08-24 06:29:42 +00004732 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004733 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004734 if (ArgExpr.isInvalid())
4735 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004736
Anders Carlsson355933d2009-08-25 03:49:14 +00004737 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004738 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004739 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004740 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004741
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004742 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004743 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00004744
4745 // Assume that extern "C" functions with variadic arguments that
4746 // return __unknown_anytype aren't *really* variadic.
4747 if (Proto->getResultType() == Context.UnknownAnyTy &&
4748 FDecl && FDecl->isExternC()) {
4749 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4750 ExprResult arg;
4751 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
4752 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
4753 else
4754 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4755 Invalid |= arg.isInvalid();
4756 AllArgs.push_back(arg.take());
4757 }
4758
4759 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4760 } else {
4761 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4762 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4763 Invalid |= Arg.isInvalid();
4764 AllArgs.push_back(Arg.take());
4765 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004766 }
4767 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004768 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004769}
4770
John McCall2979fe02011-04-12 00:42:48 +00004771/// Given a function expression of unknown-any type, try to rebuild it
4772/// to have a function type.
4773static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4774
Steve Naroff83895f72007-09-16 03:34:24 +00004775/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004776/// This provides the location of the left/right parens and a list of comma
4777/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004778ExprResult
John McCallb268a282010-08-23 23:25:46 +00004779Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004780 MultiExprArg args, SourceLocation RParenLoc,
4781 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004782 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004783
4784 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004785 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004786 if (Result.isInvalid()) return ExprError();
4787 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004788
John McCallb268a282010-08-23 23:25:46 +00004789 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004790
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004791 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004792 // If this is a pseudo-destructor expression, build the call immediately.
4793 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4794 if (NumArgs > 0) {
4795 // Pseudo-destructor calls should not have any arguments.
4796 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004797 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004798 SourceRange(Args[0]->getLocStart(),
4799 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004800
Douglas Gregorad8a3362009-09-04 17:36:40 +00004801 NumArgs = 0;
4802 }
Mike Stump11289f42009-09-09 15:08:12 +00004803
Douglas Gregorad8a3362009-09-04 17:36:40 +00004804 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004805 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004806 }
Mike Stump11289f42009-09-09 15:08:12 +00004807
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004808 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004809 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004810 // FIXME: Will need to cache the results of name lookup (including ADL) in
4811 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004812 bool Dependent = false;
4813 if (Fn->isTypeDependent())
4814 Dependent = true;
4815 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4816 Dependent = true;
4817
Peter Collingbourne41f85462011-02-09 21:07:24 +00004818 if (Dependent) {
4819 if (ExecConfig) {
4820 return Owned(new (Context) CUDAKernelCallExpr(
4821 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4822 Context.DependentTy, VK_RValue, RParenLoc));
4823 } else {
4824 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4825 Context.DependentTy, VK_RValue,
4826 RParenLoc));
4827 }
4828 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004829
4830 // Determine whether this is a call to an object (C++ [over.call.object]).
4831 if (Fn->getType()->isRecordType())
4832 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004833 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004834
John McCall2979fe02011-04-12 00:42:48 +00004835 if (Fn->getType() == Context.UnknownAnyTy) {
4836 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4837 if (result.isInvalid()) return ExprError();
4838 Fn = result.take();
4839 }
4840
John McCall10eae182009-11-30 22:42:35 +00004841 Expr *NakedFn = Fn->IgnoreParens();
4842
4843 // Determine whether this is a call to an unresolved member function.
4844 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4845 // If lookup was unresolved but not dependent (i.e. didn't find
4846 // an unresolved using declaration), it has to be an overloaded
4847 // function set, which means it must contain either multiple
4848 // declarations (all methods or method templates) or a single
4849 // method template.
4850 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor516d6722010-04-25 21:15:30 +00004851 isa<FunctionTemplateDecl>(
4852 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00004853 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00004854
John McCall2d74de92009-12-01 22:10:20 +00004855 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004856 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004857 }
4858
Douglas Gregore254f902009-02-04 00:32:51 +00004859 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00004860 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004861 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00004862 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00004863 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004864 RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004865 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004866
Anders Carlsson61914b52009-10-03 17:40:22 +00004867 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00004868 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCalle3027922010-08-25 11:45:40 +00004869 if (BO->getOpcode() == BO_PtrMemD ||
4870 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregorc8be9522010-05-04 18:18:31 +00004871 if (const FunctionProtoType *FPT
4872 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004873 QualType ResultTy = FPT->getCallResultType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004874 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004875
Douglas Gregor125fa402011-02-04 12:57:49 +00004876 // Check that the object type isn't more qualified than the
4877 // member function we're calling.
4878 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4879 Qualifiers ObjectQuals
4880 = BO->getOpcode() == BO_PtrMemD
4881 ? BO->getLHS()->getType().getQualifiers()
4882 : BO->getLHS()->getType()->getAs<PointerType>()
4883 ->getPointeeType().getQualifiers();
4884
4885 Qualifiers Difference = ObjectQuals - FuncQuals;
4886 Difference.removeObjCGCAttr();
4887 Difference.removeAddressSpace();
4888 if (Difference) {
4889 std::string QualsString = Difference.getAsString();
4890 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4891 << BO->getType().getUnqualifiedType()
4892 << QualsString
4893 << (QualsString.find(' ') == std::string::npos? 1 : 2);
4894 }
4895
John McCallb268a282010-08-23 23:25:46 +00004896 CXXMemberCallExpr *TheCall
Abramo Bagnara21e9d862010-12-03 21:39:42 +00004897 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCall7decc9e2010-11-18 06:31:45 +00004898 NumArgs, ResultTy, VK,
John McCallb268a282010-08-23 23:25:46 +00004899 RParenLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004900
4901 if (CheckCallReturnType(FPT->getResultType(),
4902 BO->getRHS()->getSourceRange().getBegin(),
John McCallb268a282010-08-23 23:25:46 +00004903 TheCall, 0))
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004904 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00004905
John McCallb268a282010-08-23 23:25:46 +00004906 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004907 RParenLoc))
4908 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00004909
John McCallb268a282010-08-23 23:25:46 +00004910 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004911 }
Anders Carlsson61914b52009-10-03 17:40:22 +00004912 }
4913 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004914 }
4915
Douglas Gregore254f902009-02-04 00:32:51 +00004916 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004917 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00004918 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004919
Eli Friedmane14b1992009-12-26 03:35:45 +00004920 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004921 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4922 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4923 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004924 RParenLoc, ExecConfig);
Douglas Gregor928479e2010-11-09 20:03:54 +00004925 }
4926
John McCall57500772009-12-16 12:17:52 +00004927 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004928 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4929 if (UnOp->getOpcode() == UO_AddrOf)
4930 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4931
John McCall57500772009-12-16 12:17:52 +00004932 if (isa<DeclRefExpr>(NakedFn))
4933 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4934
Peter Collingbourne41f85462011-02-09 21:07:24 +00004935 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4936 ExecConfig);
4937}
4938
4939ExprResult
4940Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4941 MultiExprArg execConfig, SourceLocation GGGLoc) {
4942 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4943 if (!ConfigDecl)
4944 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4945 << "cudaConfigureCall");
4946 QualType ConfigQTy = ConfigDecl->getType();
4947
4948 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4949 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4950
4951 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00004952}
4953
John McCall57500772009-12-16 12:17:52 +00004954/// BuildResolvedCallExpr - Build a call to a resolved expression,
4955/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004956/// unary-convert to an expression of function-pointer or
4957/// block-pointer type.
4958///
4959/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004960ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004961Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4962 SourceLocation LParenLoc,
4963 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004964 SourceLocation RParenLoc,
4965 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00004966 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4967
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004968 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00004969 ExprResult Result = UsualUnaryConversions(Fn);
4970 if (Result.isInvalid())
4971 return ExprError();
4972 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004973
Chris Lattner08464942007-12-28 05:29:59 +00004974 // Make the call expr early, before semantic checks. This guarantees cleanup
4975 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00004976 CallExpr *TheCall;
4977 if (Config) {
4978 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4979 cast<CallExpr>(Config),
4980 Args, NumArgs,
4981 Context.BoolTy,
4982 VK_RValue,
4983 RParenLoc);
4984 } else {
4985 TheCall = new (Context) CallExpr(Context, Fn,
4986 Args, NumArgs,
4987 Context.BoolTy,
4988 VK_RValue,
4989 RParenLoc);
4990 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004991
John McCallbebede42011-02-26 05:39:39 +00004992 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4993
4994 // Bail out early if calling a builtin with custom typechecking.
4995 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4996 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4997
John McCall31996342011-04-07 08:22:57 +00004998 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004999 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00005000 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005001 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5002 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00005003 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00005004 if (FuncT == 0)
5005 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5006 << Fn->getType() << Fn->getSourceRange());
5007 } else if (const BlockPointerType *BPT =
5008 Fn->getType()->getAs<BlockPointerType>()) {
5009 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5010 } else {
John McCall31996342011-04-07 08:22:57 +00005011 // Handle calls to expressions of unknown-any type.
5012 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00005013 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00005014 if (rewrite.isInvalid()) return ExprError();
5015 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00005016 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00005017 goto retry;
5018 }
5019
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005020 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5021 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00005022 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005023
Peter Collingbourne4b66c472011-02-23 01:53:29 +00005024 if (getLangOptions().CUDA) {
5025 if (Config) {
5026 // CUDA: Kernel calls must be to global functions
5027 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5028 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5029 << FDecl->getName() << Fn->getSourceRange());
5030
5031 // CUDA: Kernel function must have 'void' return type
5032 if (!FuncT->getResultType()->isVoidType())
5033 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5034 << Fn->getType() << Fn->getSourceRange());
5035 }
5036 }
5037
Eli Friedman3164fb12009-03-22 22:00:50 +00005038 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005039 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00005040 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005041 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00005042 return ExprError();
5043
Chris Lattner08464942007-12-28 05:29:59 +00005044 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00005045 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00005046 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005047
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005048 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00005049 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005050 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005051 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00005052 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005053 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005054
Douglas Gregord8e97de2009-04-02 15:37:10 +00005055 if (FDecl) {
5056 // Check if we have too few/too many template arguments, based
5057 // on our knowledge of the function definition.
5058 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00005059 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00005060 const FunctionProtoType *Proto
5061 = Def->getType()->getAs<FunctionProtoType>();
5062 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00005063 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5064 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00005065 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00005066
5067 // If the function we're calling isn't a function prototype, but we have
5068 // a function prototype from a prior declaratiom, use that prototype.
5069 if (!FDecl->hasPrototype())
5070 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00005071 }
5072
Steve Naroff0b661582007-08-28 23:30:39 +00005073 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00005074 for (unsigned i = 0; i != NumArgs; i++) {
5075 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00005076
5077 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00005078 InitializedEntity Entity
5079 = InitializedEntity::InitializeParameter(Context,
5080 Proto->getArgType(i));
5081 ExprResult ArgE = PerformCopyInitialization(Entity,
5082 SourceLocation(),
5083 Owned(Arg));
5084 if (ArgE.isInvalid())
5085 return true;
5086
5087 Arg = ArgE.takeAs<Expr>();
5088
5089 } else {
John Wiegley01296292011-04-08 18:41:53 +00005090 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5091
5092 if (ArgE.isInvalid())
5093 return true;
5094
5095 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00005096 }
5097
Douglas Gregor83025412010-10-26 05:45:40 +00005098 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
5099 Arg->getType(),
5100 PDiag(diag::err_call_incomplete_argument)
5101 << Arg->getSourceRange()))
5102 return ExprError();
5103
Chris Lattner08464942007-12-28 05:29:59 +00005104 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00005105 }
Steve Naroffae4143e2007-04-26 20:39:23 +00005106 }
Chris Lattner08464942007-12-28 05:29:59 +00005107
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005108 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5109 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005110 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5111 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005112
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00005113 // Check for sentinels
5114 if (NDecl)
5115 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00005116
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005117 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005118 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00005119 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005120 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00005121
John McCallbebede42011-02-26 05:39:39 +00005122 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00005123 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005124 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00005125 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005126 return ExprError();
5127 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005128
John McCallb268a282010-08-23 23:25:46 +00005129 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00005130}
5131
John McCalldadc5752010-08-24 06:29:42 +00005132ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005133Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005134 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00005135 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00005136 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00005137 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00005138
5139 TypeSourceInfo *TInfo;
5140 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5141 if (!TInfo)
5142 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5143
John McCallb268a282010-08-23 23:25:46 +00005144 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00005145}
5146
John McCalldadc5752010-08-24 06:29:42 +00005147ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00005148Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00005149 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00005150 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00005151
Eli Friedman37a186d2008-05-20 05:22:08 +00005152 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00005153 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5154 PDiag(diag::err_illegal_decl_array_incomplete_type)
5155 << SourceRange(LParenLoc,
5156 literalExpr->getSourceRange().getEnd())))
5157 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00005158 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005159 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5160 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00005161 } else if (!literalType->isDependentType() &&
5162 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00005163 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00005164 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00005165 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005166 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00005167
Douglas Gregor85dabae2009-12-16 01:38:02 +00005168 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00005169 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005170 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005171 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00005172 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00005173 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00005174 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00005175 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00005176 &literalType);
5177 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005178 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00005179 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00005180
Chris Lattner79413952008-12-04 23:50:19 +00005181 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00005182 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00005183 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005184 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00005185 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00005186
John McCall7decc9e2010-11-18 06:31:45 +00005187 // In C, compound literals are l-values for some reason.
5188 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
5189
John McCall5d7aa7f2010-01-19 22:33:45 +00005190 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00005191 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00005192}
5193
John McCalldadc5752010-08-24 06:29:42 +00005194ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00005195Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00005196 SourceLocation RBraceLoc) {
5197 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00005198 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00005199
Steve Naroff30d242c2007-09-15 18:49:24 +00005200 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00005201 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005202
Ted Kremenekac034612010-04-13 23:39:13 +00005203 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
5204 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005205 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005206 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00005207}
5208
John McCalld7646252010-11-14 08:17:51 +00005209/// Prepares for a scalar cast, performing all the necessary stages
5210/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00005211static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00005212 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5213 // Also, callers should have filtered out the invalid cases with
5214 // pointers. Everything else should be possible.
5215
John Wiegley01296292011-04-08 18:41:53 +00005216 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00005217 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00005218 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00005219
John McCall8cb679e2010-11-15 09:13:47 +00005220 switch (SrcTy->getScalarTypeKind()) {
5221 case Type::STK_MemberPointer:
5222 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00005223
John McCall8cb679e2010-11-15 09:13:47 +00005224 case Type::STK_Pointer:
5225 switch (DestTy->getScalarTypeKind()) {
5226 case Type::STK_Pointer:
5227 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00005228 CK_AnyPointerToObjCPointerCast :
5229 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00005230 case Type::STK_Bool:
5231 return CK_PointerToBoolean;
5232 case Type::STK_Integral:
5233 return CK_PointerToIntegral;
5234 case Type::STK_Floating:
5235 case Type::STK_FloatingComplex:
5236 case Type::STK_IntegralComplex:
5237 case Type::STK_MemberPointer:
5238 llvm_unreachable("illegal cast from pointer");
5239 }
5240 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005241
John McCall8cb679e2010-11-15 09:13:47 +00005242 case Type::STK_Bool: // casting from bool is like casting from an integer
5243 case Type::STK_Integral:
5244 switch (DestTy->getScalarTypeKind()) {
5245 case Type::STK_Pointer:
John Wiegley01296292011-04-08 18:41:53 +00005246 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00005247 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00005248 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005249 case Type::STK_Bool:
5250 return CK_IntegralToBoolean;
5251 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00005252 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00005253 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005254 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005255 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00005256 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5257 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00005258 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005259 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00005260 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5261 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00005262 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005263 case Type::STK_MemberPointer:
5264 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005265 }
5266 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005267
John McCall8cb679e2010-11-15 09:13:47 +00005268 case Type::STK_Floating:
5269 switch (DestTy->getScalarTypeKind()) {
5270 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005271 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00005272 case Type::STK_Bool:
5273 return CK_FloatingToBoolean;
5274 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00005275 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005276 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00005277 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5278 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00005279 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005280 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00005281 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5282 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00005283 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005284 case Type::STK_Pointer:
5285 llvm_unreachable("valid float->pointer cast?");
5286 case Type::STK_MemberPointer:
5287 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005288 }
5289 break;
5290
John McCall8cb679e2010-11-15 09:13:47 +00005291 case Type::STK_FloatingComplex:
5292 switch (DestTy->getScalarTypeKind()) {
5293 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005294 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00005295 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005296 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00005297 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00005298 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005299 if (S.Context.hasSameType(ET, DestTy))
5300 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00005301 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005302 return CK_FloatingCast;
5303 }
John McCall8cb679e2010-11-15 09:13:47 +00005304 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005305 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005306 case Type::STK_Integral:
John Wiegley01296292011-04-08 18:41:53 +00005307 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5308 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005309 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005310 case Type::STK_Pointer:
5311 llvm_unreachable("valid complex float->pointer cast?");
5312 case Type::STK_MemberPointer:
5313 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005314 }
5315 break;
5316
John McCall8cb679e2010-11-15 09:13:47 +00005317 case Type::STK_IntegralComplex:
5318 switch (DestTy->getScalarTypeKind()) {
5319 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005320 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005321 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005322 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00005323 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00005324 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005325 if (S.Context.hasSameType(ET, DestTy))
5326 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00005327 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005328 return CK_IntegralCast;
5329 }
John McCall8cb679e2010-11-15 09:13:47 +00005330 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005331 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005332 case Type::STK_Floating:
John Wiegley01296292011-04-08 18:41:53 +00005333 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5334 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005335 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005336 case Type::STK_Pointer:
5337 llvm_unreachable("valid complex int->pointer cast?");
5338 case Type::STK_MemberPointer:
5339 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005340 }
5341 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00005342 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005343
John McCalld7646252010-11-14 08:17:51 +00005344 llvm_unreachable("Unhandled scalar cast");
5345 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00005346}
5347
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005348/// CheckCastTypes - Check type constraints for casting between types.
John Wiegley01296292011-04-08 18:41:53 +00005349ExprResult Sema::CheckCastTypes(SourceRange TyR, QualType castType,
5350 Expr *castExpr, CastKind& Kind, ExprValueKind &VK,
5351 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00005352 if (castExpr->getType() == Context.UnknownAnyTy)
5353 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
5354
Sebastian Redl9f831db2009-07-25 15:41:38 +00005355 if (getLangOptions().CPlusPlus)
Douglas Gregor15417cf2010-11-03 00:35:38 +00005356 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
5357 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00005358 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00005359 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00005360
John McCall3aef3d82011-04-10 19:13:55 +00005361 assert(!castExpr->getType()->isPlaceholderType());
5362
John McCall7decc9e2010-11-18 06:31:45 +00005363 // We only support r-value casts in C.
5364 VK = VK_RValue;
5365
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005366 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5367 // type needs to be scalar.
5368 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00005369 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley01296292011-04-08 18:41:53 +00005370 ExprResult castExprRes = IgnoredValueConversions(castExpr);
5371 if (castExprRes.isInvalid())
5372 return ExprError();
5373 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00005374
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005375 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00005376 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00005377 return Owned(castExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00005378 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005379
John Wiegley01296292011-04-08 18:41:53 +00005380 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
5381 if (castExprRes.isInvalid())
5382 return ExprError();
5383 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00005384
Eli Friedmane98194d2010-07-17 20:43:49 +00005385 if (RequireCompleteType(TyR.getBegin(), castType,
5386 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00005387 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00005388
Anders Carlssonef918ac2009-10-16 02:35:04 +00005389 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005390 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005391 (castType->isStructureType() || castType->isUnionType())) {
5392 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00005393 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005394 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5395 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005396 Kind = CK_NoOp;
John Wiegley01296292011-04-08 18:41:53 +00005397 return Owned(castExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00005398 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005399
Anders Carlsson525b76b2009-10-16 02:48:28 +00005400 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005401 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005402 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005403 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005404 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005405 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005406 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00005407 castExpr->getType()) &&
5408 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005409 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5410 << castExpr->getSourceRange();
5411 break;
5412 }
5413 }
John Wiegley01296292011-04-08 18:41:53 +00005414 if (Field == FieldEnd) {
5415 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005416 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005417 return ExprError();
5418 }
John McCalle3027922010-08-25 11:45:40 +00005419 Kind = CK_ToUnion;
John Wiegley01296292011-04-08 18:41:53 +00005420 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005421 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005422
Anders Carlsson525b76b2009-10-16 02:48:28 +00005423 // Reject any other conversions to non-scalar types.
John Wiegley01296292011-04-08 18:41:53 +00005424 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlsson525b76b2009-10-16 02:48:28 +00005425 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005426 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005427 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005428
John McCalld7646252010-11-14 08:17:51 +00005429 // The type we're casting to is known to be a scalar or vector.
5430
5431 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005432 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00005433 !castExpr->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005434 Diag(castExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005435 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005436 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005437 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005438 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005439
5440 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00005441 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005442
Anton Yartsev28ccef72011-03-27 09:32:40 +00005443 if (castType->isVectorType()) {
5444 if (castType->getAs<VectorType>()->getVectorKind() ==
5445 VectorType::AltiVecVector &&
5446 (castExpr->getType()->isIntegerType() ||
5447 castExpr->getType()->isFloatingType())) {
5448 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00005449 return Owned(castExpr);
5450 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
5451 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00005452 } else
John Wiegley01296292011-04-08 18:41:53 +00005453 return Owned(castExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00005454 }
John Wiegley01296292011-04-08 18:41:53 +00005455 if (castExpr->getType()->isVectorType()) {
5456 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
5457 return ExprError();
5458 else
5459 return Owned(castExpr);
5460 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00005461
John McCalld7646252010-11-14 08:17:51 +00005462 // The source and target types are both scalars, i.e.
5463 // - arithmetic types (fundamental, enum, and complex)
5464 // - all kinds of pointers
5465 // Note that member pointers were filtered out with C++, above.
5466
John Wiegley01296292011-04-08 18:41:53 +00005467 if (isa<ObjCSelectorExpr>(castExpr)) {
5468 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
5469 return ExprError();
5470 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005471
John McCalld7646252010-11-14 08:17:51 +00005472 // If either type is a pointer, the other type has to be either an
5473 // integer or a pointer.
Anders Carlsson525b76b2009-10-16 02:48:28 +00005474 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005475 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005476 if (!castExprType->isIntegralType(Context) &&
John Wiegley01296292011-04-08 18:41:53 +00005477 castExprType->isArithmeticType()) {
5478 Diag(castExpr->getLocStart(),
5479 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005480 << castExprType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005481 return ExprError();
5482 }
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005483 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley01296292011-04-08 18:41:53 +00005484 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
5485 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005486 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005487 return ExprError();
5488 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005489 }
Anders Carlsson094c4592009-10-18 18:12:03 +00005490
John Wiegley01296292011-04-08 18:41:53 +00005491 castExprRes = Owned(castExpr);
5492 Kind = PrepareScalarCast(*this, castExprRes, castType);
5493 if (castExprRes.isInvalid())
5494 return ExprError();
5495 castExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00005496
John McCalld7646252010-11-14 08:17:51 +00005497 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00005498 CheckCastAlign(castExpr, castType, TyR);
5499
John Wiegley01296292011-04-08 18:41:53 +00005500 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005501}
5502
Anders Carlsson525b76b2009-10-16 02:48:28 +00005503bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00005504 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00005505 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005506
Anders Carlssonde71adf2007-11-27 05:51:55 +00005507 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00005508 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00005509 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00005510 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00005511 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00005512 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005513 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005514 } else
5515 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00005516 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005517 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005518
John McCalle3027922010-08-25 11:45:40 +00005519 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005520 return false;
5521}
5522
John Wiegley01296292011-04-08 18:41:53 +00005523ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5524 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00005525 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005526
Anders Carlsson43d70f82009-10-16 05:23:41 +00005527 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005528
Nate Begemanc8961a42009-06-27 22:05:55 +00005529 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5530 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00005531 if (SrcTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005532 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
5533 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00005534 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00005535 return ExprError();
5536 }
John McCalle3027922010-08-25 11:45:40 +00005537 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00005538 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00005539 }
5540
Nate Begemanbd956c42009-06-28 02:36:38 +00005541 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00005542 // conversion will take place first from scalar to elt type, and then
5543 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00005544 if (SrcTy->isPointerType())
5545 return Diag(R.getBegin(),
5546 diag::err_invalid_conversion_between_vector_and_scalar)
5547 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00005548
5549 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00005550 ExprResult CastExprRes = Owned(CastExpr);
5551 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
5552 if (CastExprRes.isInvalid())
5553 return ExprError();
5554 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005555
John McCalle3027922010-08-25 11:45:40 +00005556 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00005557 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00005558}
5559
John McCalldadc5752010-08-24 06:29:42 +00005560ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005561Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005562 SourceLocation RParenLoc, Expr *castExpr) {
5563 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00005564 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00005565
John McCall97513962010-01-15 18:39:57 +00005566 TypeSourceInfo *castTInfo;
5567 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5568 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00005569 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00005570
Nate Begeman5ec4b312009-08-10 23:49:36 +00005571 // If the Expr being casted is a ParenListExpr, handle it specially.
5572 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00005573 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00005574 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00005575
John McCallb268a282010-08-23 23:25:46 +00005576 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00005577}
5578
John McCalldadc5752010-08-24 06:29:42 +00005579ExprResult
John McCallebe54742010-01-15 18:56:44 +00005580Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00005581 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00005582 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00005583 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00005584 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00005585 ExprResult CastResult =
5586 CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
5587 Kind, VK, BasePath);
5588 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005589 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005590 castExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00005591
John McCallcf142162010-08-07 06:22:56 +00005592 return Owned(CStyleCastExpr::Create(Context,
John Wiegley01296292011-04-08 18:41:53 +00005593 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00005594 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00005595 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00005596}
5597
Nate Begeman5ec4b312009-08-10 23:49:36 +00005598/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5599/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00005600ExprResult
John McCallb268a282010-08-23 23:25:46 +00005601Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005602 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5603 if (!E)
5604 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00005605
John McCalldadc5752010-08-24 06:29:42 +00005606 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00005607
Nate Begeman5ec4b312009-08-10 23:49:36 +00005608 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00005609 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5610 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00005611
John McCallb268a282010-08-23 23:25:46 +00005612 if (Result.isInvalid()) return ExprError();
5613
5614 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005615}
5616
John McCalldadc5752010-08-24 06:29:42 +00005617ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00005618Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00005619 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00005620 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00005621 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00005622 QualType Ty = TInfo->getType();
Anton Yartsev28ccef72011-03-27 09:32:40 +00005623 bool isVectorLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00005624
Anton Yartsev28ccef72011-03-27 09:32:40 +00005625 // Check for an altivec or OpenCL literal,
John Thompson781ad172010-06-30 22:55:51 +00005626 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005627 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5628 if (PE->getNumExprs() == 0) {
5629 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5630 return ExprError();
5631 }
John Thompson781ad172010-06-30 22:55:51 +00005632 if (PE->getNumExprs() == 1) {
5633 if (!PE->getExpr(0)->getType()->isVectorType())
Anton Yartsev28ccef72011-03-27 09:32:40 +00005634 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005635 }
5636 else
Anton Yartsev28ccef72011-03-27 09:32:40 +00005637 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005638 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00005639
Anton Yartsev28ccef72011-03-27 09:32:40 +00005640 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
John Thompson781ad172010-06-30 22:55:51 +00005641 // then handle it as such.
Anton Yartsev28ccef72011-03-27 09:32:40 +00005642 if (isVectorLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005643 llvm::SmallVector<Expr *, 8> initExprs;
Anton Yartsev28ccef72011-03-27 09:32:40 +00005644 // '(...)' form of vector initialization in AltiVec: the number of
5645 // initializers must be one or must match the size of the vector.
5646 // If a single value is specified in the initializer then it will be
5647 // replicated to all the components of the vector
5648 if (Ty->getAs<VectorType>()->getVectorKind() ==
5649 VectorType::AltiVecVector) {
5650 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5651 // The number of initializers must be one or must match the size of the
5652 // vector. If a single value is specified in the initializer then it will
5653 // be replicated to all the components of the vector
5654 if (PE->getNumExprs() == 1) {
5655 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00005656 ExprResult Literal = Owned(PE->getExpr(0));
5657 Literal = ImpCastExprToType(Literal.take(), ElemTy,
5658 PrepareScalarCast(*this, Literal, ElemTy));
5659 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
Anton Yartsev28ccef72011-03-27 09:32:40 +00005660 }
5661 else if (PE->getNumExprs() < numElems) {
5662 Diag(PE->getExprLoc(),
5663 diag::err_incorrect_number_of_vector_initializers);
5664 return ExprError();
5665 }
5666 else
5667 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5668 initExprs.push_back(PE->getExpr(i));
5669 }
5670 else
5671 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5672 initExprs.push_back(PE->getExpr(i));
Nate Begeman5ec4b312009-08-10 23:49:36 +00005673
5674 // FIXME: This means that pretty-printing the final AST will produce curly
5675 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00005676 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5677 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00005678 initExprs.size(), RParenLoc);
5679 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00005680 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005681 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005682 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00005683 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00005684 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00005685 if (Result.isInvalid()) return ExprError();
5686 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005687 }
5688}
5689
John McCalldadc5752010-08-24 06:29:42 +00005690ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00005691 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005692 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00005693 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005694 unsigned nexprs = Val.size();
5695 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005696 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5697 Expr *expr;
5698 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5699 expr = new (Context) ParenExpr(L, R, exprs[0]);
5700 else
5701 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005702 return Owned(expr);
5703}
5704
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005705/// \brief Emit a specialized diagnostic when one expression is a null pointer
5706/// constant and the other is not a pointer.
5707bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5708 SourceLocation QuestionLoc) {
5709 Expr *NullExpr = LHS;
5710 Expr *NonPointerExpr = RHS;
5711 Expr::NullPointerConstantKind NullKind =
5712 NullExpr->isNullPointerConstant(Context,
5713 Expr::NPC_ValueDependentIsNotNull);
5714
5715 if (NullKind == Expr::NPCK_NotNull) {
5716 NullExpr = RHS;
5717 NonPointerExpr = LHS;
5718 NullKind =
5719 NullExpr->isNullPointerConstant(Context,
5720 Expr::NPC_ValueDependentIsNotNull);
5721 }
5722
5723 if (NullKind == Expr::NPCK_NotNull)
5724 return false;
5725
5726 if (NullKind == Expr::NPCK_ZeroInteger) {
5727 // In this case, check to make sure that we got here from a "NULL"
5728 // string in the source code.
5729 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00005730 SourceLocation loc = NullExpr->getExprLoc();
5731 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005732 return false;
5733 }
5734
5735 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5736 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5737 << NonPointerExpr->getType() << DiagType
5738 << NonPointerExpr->getSourceRange();
5739 return true;
5740}
5741
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005742/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5743/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00005744/// C99 6.5.15
John Wiegley01296292011-04-08 18:41:53 +00005745QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005746 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00005747 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00005748
John McCall3aef3d82011-04-10 19:13:55 +00005749 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00005750 if (!lhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005751 LHS = move(lhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005752
John McCall3aef3d82011-04-10 19:13:55 +00005753 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00005754 if (!rhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005755 RHS = move(rhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005756
Sebastian Redl1a99f442009-04-16 17:51:27 +00005757 // C++ is sufficiently different to merit its own checker.
5758 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00005759 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00005760
5761 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005762 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005763
John Wiegley01296292011-04-08 18:41:53 +00005764 Cond = UsualUnaryConversions(Cond.take());
5765 if (Cond.isInvalid())
5766 return QualType();
5767 LHS = UsualUnaryConversions(LHS.take());
5768 if (LHS.isInvalid())
5769 return QualType();
5770 RHS = UsualUnaryConversions(RHS.take());
5771 if (RHS.isInvalid())
5772 return QualType();
5773
5774 QualType CondTy = Cond.get()->getType();
5775 QualType LHSTy = LHS.get()->getType();
5776 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00005777
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005778 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005779 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00005780 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5781 // Throw an error if its not either.
5782 if (getLangOptions().OpenCL) {
5783 if (!CondTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005784 Diag(Cond.get()->getLocStart(),
Nate Begemanabb5a732010-09-20 22:41:17 +00005785 diag::err_typecheck_cond_expect_scalar_or_vector)
5786 << CondTy;
5787 return QualType();
5788 }
5789 }
5790 else {
John Wiegley01296292011-04-08 18:41:53 +00005791 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005792 << CondTy;
5793 return QualType();
5794 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005795 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005796
Chris Lattnere2949f42008-01-06 22:42:25 +00005797 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005798 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5799 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00005800
Nate Begemanabb5a732010-09-20 22:41:17 +00005801 // OpenCL: If the condition is a vector, and both operands are scalar,
5802 // attempt to implicity convert them to the vector type to act like the
5803 // built in select.
5804 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5805 // Both operands should be of scalar type.
5806 if (!LHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00005807 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005808 << CondTy;
5809 return QualType();
5810 }
5811 if (!RHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00005812 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005813 << CondTy;
5814 return QualType();
5815 }
5816 // Implicity convert these scalars to the type of the condition.
John Wiegley01296292011-04-08 18:41:53 +00005817 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5818 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begemanabb5a732010-09-20 22:41:17 +00005819 }
5820
Chris Lattnere2949f42008-01-06 22:42:25 +00005821 // If both operands have arithmetic type, do the usual arithmetic conversions
5822 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00005823 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5824 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005825 if (LHS.isInvalid() || RHS.isInvalid())
5826 return QualType();
5827 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00005828 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005829
Chris Lattnere2949f42008-01-06 22:42:25 +00005830 // If both operands are the same structure or union type, the result is that
5831 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005832 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5833 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005834 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005835 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005836 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005837 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005838 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005839 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005840
Chris Lattnere2949f42008-01-06 22:42:25 +00005841 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005842 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005843 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5844 if (!LHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00005845 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5846 << RHS.get()->getSourceRange();
Chris Lattner432cff52009-02-18 04:28:32 +00005847 if (!RHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00005848 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5849 << LHS.get()->getSourceRange();
5850 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
5851 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00005852 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00005853 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00005854 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5855 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00005856 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00005857 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005858 // promote the null to a pointer.
John Wiegley01296292011-04-08 18:41:53 +00005859 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005860 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005861 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005862 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00005863 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5864 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005865 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005866 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005867
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005868 // All objective-c pointer type analysis is done here.
5869 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5870 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005871 if (LHS.isInvalid() || RHS.isInvalid())
5872 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005873 if (!compositeType.isNull())
5874 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005875
5876
Steve Naroff05efa972009-07-01 14:36:47 +00005877 // Handle block pointer types.
5878 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5879 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5880 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5881 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00005882 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5883 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005884 return destType;
5885 }
5886 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005887 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005888 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00005889 }
Steve Naroff05efa972009-07-01 14:36:47 +00005890 // We have 2 block pointer types.
5891 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5892 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00005893 return LHSTy;
5894 }
Steve Naroff05efa972009-07-01 14:36:47 +00005895 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005896 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5897 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005898
Steve Naroff05efa972009-07-01 14:36:47 +00005899 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5900 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00005901 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00005902 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00005903 // In this situation, we assume void* type. No especially good
5904 // reason, but this is what gcc does, and we do have to pick
5905 // to get a consistent AST.
5906 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00005907 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5908 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00005909 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005910 }
Steve Naroff05efa972009-07-01 14:36:47 +00005911 // The block pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00005912 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5913 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00005914 return LHSTy;
5915 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005916
Steve Naroff05efa972009-07-01 14:36:47 +00005917 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5918 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5919 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005920 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5921 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00005922
5923 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5924 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5925 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00005926 QualType destPointee
5927 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005928 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005929 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005930 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005931 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005932 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005933 return destType;
5934 }
5935 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005936 QualType destPointee
5937 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005938 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005939 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005940 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005941 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005942 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005943 return destType;
5944 }
5945
5946 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5947 // Two identical pointer types are always compatible.
5948 return LHSTy;
5949 }
5950 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5951 rhptee.getUnqualifiedType())) {
5952 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00005953 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005954 // In this situation, we assume void* type. No especially good
5955 // reason, but this is what gcc does, and we do have to pick
5956 // to get a consistent AST.
5957 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00005958 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5959 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005960 return incompatTy;
5961 }
5962 // The pointer types are compatible.
5963 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5964 // differently qualified versions of compatible types, the result type is
5965 // a pointer to an appropriately qualified version of the *composite*
5966 // type.
5967 // FIXME: Need to calculate the composite type.
5968 // FIXME: Need to add qualifiers
John Wiegley01296292011-04-08 18:41:53 +00005969 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5970 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005971 return LHSTy;
5972 }
Mike Stump11289f42009-09-09 15:08:12 +00005973
John McCalle84af4e2010-11-13 01:35:44 +00005974 // GCC compatibility: soften pointer/integer mismatch. Note that
5975 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00005976 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5977 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00005978 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5979 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005980 return RHSTy;
5981 }
5982 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5983 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00005984 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5985 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005986 return LHSTy;
5987 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00005988
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005989 // Emit a better diagnostic if one of the expressions is a null pointer
5990 // constant and the other is not a pointer type. In this case, the user most
5991 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005992 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005993 return QualType();
5994
Chris Lattnere2949f42008-01-06 22:42:25 +00005995 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005996 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005997 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005998 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005999}
6000
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006001/// FindCompositeObjCPointerType - Helper method to find composite type of
6002/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00006003QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006004 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00006005 QualType LHSTy = LHS.get()->getType();
6006 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006007
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006008 // Handle things like Class and struct objc_class*. Here we case the result
6009 // to the pseudo-builtin, because that will be implicitly cast back to the
6010 // redefinition type if an attempt is made to access its fields.
6011 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00006012 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006013 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006014 return LHSTy;
6015 }
6016 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00006017 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006018 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006019 return RHSTy;
6020 }
6021 // And the same for struct objc_object* / id
6022 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00006023 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006024 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006025 return LHSTy;
6026 }
6027 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00006028 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006029 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006030 return RHSTy;
6031 }
6032 // And the same for struct objc_selector* / SEL
6033 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00006034 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006035 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006036 return LHSTy;
6037 }
6038 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00006039 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006040 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006041 return RHSTy;
6042 }
6043 // Check constraints for Objective-C object pointers types.
6044 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006045
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006046 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6047 // Two identical object pointer types are always compatible.
6048 return LHSTy;
6049 }
6050 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
6051 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
6052 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006053
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006054 // If both operands are interfaces and either operand can be
6055 // assigned to the other, use that type as the composite
6056 // type. This allows
6057 // xxx ? (A*) a : (B*) b
6058 // where B is a subclass of A.
6059 //
6060 // Additionally, as for assignment, if either type is 'id'
6061 // allow silent coercion. Finally, if the types are
6062 // incompatible then make sure to use 'id' as the composite
6063 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006064
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006065 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6066 // It could return the composite type.
6067 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6068 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6069 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6070 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6071 } else if ((LHSTy->isObjCQualifiedIdType() ||
6072 RHSTy->isObjCQualifiedIdType()) &&
6073 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6074 // Need to handle "id<xx>" explicitly.
6075 // GCC allows qualified id and any Objective-C type to devolve to
6076 // id. Currently localizing to here until clear this should be
6077 // part of ObjCQualifiedIdTypesAreCompatible.
6078 compositeType = Context.getObjCIdType();
6079 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6080 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006081 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006082 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
6083 ;
6084 else {
6085 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6086 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00006087 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006088 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00006089 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6090 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006091 return incompatTy;
6092 }
6093 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00006094 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
6095 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006096 return compositeType;
6097 }
6098 // Check Objective-C object pointer types and 'void *'
6099 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6100 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6101 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6102 QualType destPointee
6103 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6104 QualType destType = Context.getPointerType(destPointee);
6105 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00006106 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006107 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00006108 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006109 return destType;
6110 }
6111 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6112 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6113 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6114 QualType destPointee
6115 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6116 QualType destType = Context.getPointerType(destPointee);
6117 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00006118 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006119 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00006120 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006121 return destType;
6122 }
6123 return QualType();
6124}
6125
Steve Naroff83895f72007-09-16 03:34:24 +00006126/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00006127/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00006128ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00006129 SourceLocation ColonLoc,
6130 Expr *CondExpr, Expr *LHSExpr,
6131 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00006132 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6133 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00006134 OpaqueValueExpr *opaqueValue = 0;
6135 Expr *commonExpr = 0;
6136 if (LHSExpr == 0) {
6137 commonExpr = CondExpr;
6138
6139 // We usually want to apply unary conversions *before* saving, except
6140 // in the special case of a C++ l-value conditional.
6141 if (!(getLangOptions().CPlusPlus
6142 && !commonExpr->isTypeDependent()
6143 && commonExpr->getValueKind() == RHSExpr->getValueKind()
6144 && commonExpr->isGLValue()
6145 && commonExpr->isOrdinaryOrBitFieldObject()
6146 && RHSExpr->isOrdinaryOrBitFieldObject()
6147 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00006148 ExprResult commonRes = UsualUnaryConversions(commonExpr);
6149 if (commonRes.isInvalid())
6150 return ExprError();
6151 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00006152 }
6153
6154 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6155 commonExpr->getType(),
6156 commonExpr->getValueKind(),
6157 commonExpr->getObjectKind());
6158 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00006159 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00006160
John McCall7decc9e2010-11-18 06:31:45 +00006161 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00006162 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00006163 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
6164 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00006165 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00006166 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6167 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006168 return ExprError();
6169
John McCallc07a0c72011-02-17 10:25:35 +00006170 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00006171 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
6172 LHS.take(), ColonLoc,
6173 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00006174
6175 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00006176 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
6177 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00006178}
6179
John McCallaba90822011-01-31 23:13:11 +00006180// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00006181// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00006182// routine is it effectively iqnores the qualifiers on the top level pointee.
6183// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6184// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00006185static Sema::AssignConvertType
6186checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6187 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6188 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006189
Steve Naroff1f4d7272007-05-11 04:00:31 +00006190 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00006191 const Type *lhptee, *rhptee;
6192 Qualifiers lhq, rhq;
6193 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
6194 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006195
John McCallaba90822011-01-31 23:13:11 +00006196 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006197
6198 // C99 6.5.16.1p1: This following citation is common to constraints
6199 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6200 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00006201 Qualifiers lq;
6202
6203 if (!lhq.compatiblyIncludes(rhq)) {
6204 // Treat address-space mismatches as fatal. TODO: address subspaces
6205 if (lhq.getAddressSpace() != rhq.getAddressSpace())
6206 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6207
John McCall78535952011-03-26 02:56:45 +00006208 // It's okay to add or remove GC qualifiers when converting to
6209 // and from void*.
6210 else if (lhq.withoutObjCGCAttr().compatiblyIncludes(rhq.withoutObjCGCAttr())
6211 && (lhptee->isVoidType() || rhptee->isVoidType()))
6212 ; // keep old
6213
John McCall4fff8f62011-02-01 00:10:29 +00006214 // For GCC compatibility, other qualifier mismatches are treated
6215 // as still compatible in C.
6216 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6217 }
Steve Naroff3f597292007-05-11 22:18:03 +00006218
Mike Stump4e1f26a2009-02-19 03:04:26 +00006219 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6220 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00006221 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00006222 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006223 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00006224 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006225
Chris Lattner0a788432008-01-03 22:56:36 +00006226 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006227 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00006228 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00006229 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006230
Chris Lattner0a788432008-01-03 22:56:36 +00006231 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006232 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00006233 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00006234
6235 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006236 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00006237 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00006238 }
John McCall4fff8f62011-02-01 00:10:29 +00006239
Mike Stump4e1f26a2009-02-19 03:04:26 +00006240 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00006241 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00006242 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6243 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00006244 // Check if the pointee types are compatible ignoring the sign.
6245 // We explicitly check for char so that we catch "char" vs
6246 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00006247 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00006248 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006249 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00006250 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006251
Chris Lattnerec3a1562009-10-17 20:33:28 +00006252 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00006253 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006254 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00006255 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00006256
John McCall4fff8f62011-02-01 00:10:29 +00006257 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00006258 // Types are compatible ignoring the sign. Qualifier incompatibility
6259 // takes priority over sign incompatibility because the sign
6260 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00006261 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00006262 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00006263
John McCallaba90822011-01-31 23:13:11 +00006264 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00006265 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006266
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006267 // If we are a multi-level pointer, it's possible that our issue is simply
6268 // one of qualification - e.g. char ** -> const char ** is not allowed. If
6269 // the eventual target type is the same and the pointers have the same
6270 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00006271 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006272 do {
John McCall4fff8f62011-02-01 00:10:29 +00006273 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6274 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00006275 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006276
John McCall4fff8f62011-02-01 00:10:29 +00006277 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00006278 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006279 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006280
Eli Friedman80160bd2009-03-22 23:59:44 +00006281 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00006282 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00006283 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006284 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00006285}
6286
John McCallaba90822011-01-31 23:13:11 +00006287/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00006288/// block pointer types are compatible or whether a block and normal pointer
6289/// are compatible. It is more restrict than comparing two function pointer
6290// types.
John McCallaba90822011-01-31 23:13:11 +00006291static Sema::AssignConvertType
6292checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
6293 QualType rhsType) {
6294 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6295 assert(rhsType.isCanonical() && "RHS not canonicalized!");
6296
Steve Naroff081c7422008-09-04 15:10:53 +00006297 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006298
Steve Naroff081c7422008-09-04 15:10:53 +00006299 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00006300 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
6301 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006302
John McCallaba90822011-01-31 23:13:11 +00006303 // In C++, the types have to match exactly.
6304 if (S.getLangOptions().CPlusPlus)
6305 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006306
John McCallaba90822011-01-31 23:13:11 +00006307 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006308
Steve Naroff081c7422008-09-04 15:10:53 +00006309 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00006310 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6311 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006312
John McCallaba90822011-01-31 23:13:11 +00006313 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
6314 return Sema::IncompatibleBlockPointer;
6315
Steve Naroff081c7422008-09-04 15:10:53 +00006316 return ConvTy;
6317}
6318
John McCallaba90822011-01-31 23:13:11 +00006319/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006320/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00006321static Sema::AssignConvertType
6322checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6323 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
6324 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
6325
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006326 if (lhsType->isObjCBuiltinType()) {
6327 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00006328 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
6329 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00006330 return Sema::IncompatiblePointer;
6331 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006332 }
6333 if (rhsType->isObjCBuiltinType()) {
6334 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00006335 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
6336 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00006337 return Sema::IncompatiblePointer;
6338 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006339 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006340 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006341 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006342 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006343 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006344
John McCallaba90822011-01-31 23:13:11 +00006345 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
6346 return Sema::CompatiblePointerDiscardsQualifiers;
6347
6348 if (S.Context.typesAreCompatible(lhsType, rhsType))
6349 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006350 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00006351 return Sema::IncompatibleObjCQualifiedId;
6352 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006353}
6354
John McCall29600e12010-11-16 02:32:08 +00006355Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00006356Sema::CheckAssignmentConstraints(SourceLocation Loc,
6357 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00006358 // Fake up an opaque expression. We don't actually care about what
6359 // cast operations are required, so if CheckAssignmentConstraints
6360 // adds casts to this they'll be wasted, but fortunately that doesn't
6361 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00006362 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00006363 ExprResult rhsPtr = &rhs;
John McCall29600e12010-11-16 02:32:08 +00006364 CastKind K = CK_Invalid;
6365
6366 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
6367}
6368
Mike Stump4e1f26a2009-02-19 03:04:26 +00006369/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6370/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00006371/// pointers. Here are some objectionable examples that GCC considers warnings:
6372///
6373/// int a, *pint;
6374/// short *pshort;
6375/// struct foo *pfoo;
6376///
6377/// pint = pshort; // warning: assignment from incompatible pointer type
6378/// a = pint; // warning: assignment makes integer from pointer without a cast
6379/// pint = a; // warning: assignment makes pointer from integer without a cast
6380/// pint = pfoo; // warning: assignment from incompatible pointer type
6381///
6382/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00006383/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00006384///
John McCall8cb679e2010-11-15 09:13:47 +00006385/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00006386Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006387Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCall8cb679e2010-11-15 09:13:47 +00006388 CastKind &Kind) {
John Wiegley01296292011-04-08 18:41:53 +00006389 QualType rhsType = rhs.get()->getType();
John McCall29600e12010-11-16 02:32:08 +00006390
Chris Lattnera52c2f22008-01-04 23:18:45 +00006391 // Get canonical types. We're not formatting these types, just comparing
6392 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00006393 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
6394 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00006395
John McCalle5255932011-01-31 22:28:28 +00006396 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00006397 if (lhsType == rhsType) {
6398 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00006399 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00006400 }
6401
Douglas Gregor6b754842008-10-28 00:22:11 +00006402 // If the left-hand side is a reference type, then we are in a
6403 // (rare!) case where we've allowed the use of references in C,
6404 // e.g., as a parameter type in a built-in function. In this case,
6405 // just make sure that the type referenced is compatible with the
6406 // right-hand side type. The caller is responsible for adjusting
6407 // lhsType so that the resulting expression does not have reference
6408 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006409 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00006410 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
6411 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00006412 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006413 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00006414 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00006415 }
John McCalle5255932011-01-31 22:28:28 +00006416
Nate Begemanbd956c42009-06-28 02:36:38 +00006417 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6418 // to the same ExtVector type.
6419 if (lhsType->isExtVectorType()) {
6420 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00006421 return Incompatible;
6422 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00006423 // CK_VectorSplat does T -> vector T, so first cast to the
6424 // element type.
6425 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
6426 if (elType != rhsType) {
6427 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley01296292011-04-08 18:41:53 +00006428 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00006429 }
6430 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00006431 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006432 }
Nate Begemanbd956c42009-06-28 02:36:38 +00006433 }
Mike Stump11289f42009-09-09 15:08:12 +00006434
John McCalle5255932011-01-31 22:28:28 +00006435 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00006436 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006437 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00006438 // Allow assignments of an AltiVec vector type to an equivalent GCC
6439 // vector type and vice versa
6440 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6441 Kind = CK_BitCast;
6442 return Compatible;
6443 }
6444
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006445 // If we are allowing lax vector conversions, and LHS and RHS are both
6446 // vectors, the total size only needs to be the same. This is a bitcast;
6447 // no bits are changed but the result type is different.
6448 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00006449 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00006450 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006451 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00006452 }
Chris Lattner881a2122008-01-04 23:32:24 +00006453 }
6454 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006455 }
Eli Friedman3360d892008-05-30 18:07:22 +00006456
John McCalle5255932011-01-31 22:28:28 +00006457 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00006458 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00006459 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00006460 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00006461 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006462 }
Eli Friedman3360d892008-05-30 18:07:22 +00006463
John McCalle5255932011-01-31 22:28:28 +00006464 // Conversions to normal pointers.
6465 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6466 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00006467 if (isa<PointerType>(rhsType)) {
6468 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006469 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00006470 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006471
John McCalle5255932011-01-31 22:28:28 +00006472 // int -> T*
6473 if (rhsType->isIntegerType()) {
6474 Kind = CK_IntegralToPointer; // FIXME: null?
6475 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006476 }
John McCalle5255932011-01-31 22:28:28 +00006477
6478 // C pointers are not compatible with ObjC object pointers,
6479 // with two exceptions:
6480 if (isa<ObjCObjectPointerType>(rhsType)) {
6481 // - conversions to void*
6482 if (lhsPointer->getPointeeType()->isVoidType()) {
6483 Kind = CK_AnyPointerToObjCPointerCast;
6484 return Compatible;
6485 }
6486
6487 // - conversions from 'Class' to the redefinition type
6488 if (rhsType->isObjCClassType() &&
6489 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006490 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006491 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006492 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006493
John McCalle5255932011-01-31 22:28:28 +00006494 Kind = CK_BitCast;
6495 return IncompatiblePointer;
6496 }
6497
6498 // U^ -> void*
6499 if (rhsType->getAs<BlockPointerType>()) {
6500 if (lhsPointer->getPointeeType()->isVoidType()) {
6501 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006502 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006503 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006504 }
John McCalle5255932011-01-31 22:28:28 +00006505
Steve Naroff081c7422008-09-04 15:10:53 +00006506 return Incompatible;
6507 }
6508
John McCalle5255932011-01-31 22:28:28 +00006509 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00006510 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006511 // U^ -> T^
6512 if (rhsType->isBlockPointerType()) {
6513 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00006514 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006515 }
6516
6517 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006518 if (rhsType->isIntegerType()) {
6519 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00006520 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006521 }
6522
John McCalle5255932011-01-31 22:28:28 +00006523 // id -> T^
6524 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6525 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006526 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006527 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006528
John McCalle5255932011-01-31 22:28:28 +00006529 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006530 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00006531 if (RHSPT->getPointeeType()->isVoidType()) {
6532 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006533 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006534 }
John McCall8cb679e2010-11-15 09:13:47 +00006535
Chris Lattnera52c2f22008-01-04 23:18:45 +00006536 return Incompatible;
6537 }
6538
John McCalle5255932011-01-31 22:28:28 +00006539 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006540 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006541 // A* -> B*
6542 if (rhsType->isObjCObjectPointerType()) {
6543 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006544 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006545 }
6546
6547 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00006548 if (rhsType->isIntegerType()) {
6549 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00006550 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006551 }
6552
John McCalle5255932011-01-31 22:28:28 +00006553 // In general, C pointers are not compatible with ObjC object pointers,
6554 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00006555 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006556 // - conversions from 'void*'
6557 if (rhsType->isVoidPointerType()) {
6558 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006559 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006560 }
6561
6562 // - conversions to 'Class' from its redefinition type
6563 if (lhsType->isObjCClassType() &&
6564 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6565 Kind = CK_BitCast;
6566 return Compatible;
6567 }
6568
6569 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006570 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006571 }
John McCalle5255932011-01-31 22:28:28 +00006572
6573 // T^ -> A*
6574 if (rhsType->isBlockPointerType()) {
6575 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006576 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006577 }
6578
Steve Naroff7cae42b2009-07-10 23:34:53 +00006579 return Incompatible;
6580 }
John McCalle5255932011-01-31 22:28:28 +00006581
6582 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00006583 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006584 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006585 if (lhsType == Context.BoolTy) {
6586 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00006587 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006588 }
Eli Friedman3360d892008-05-30 18:07:22 +00006589
John McCalle5255932011-01-31 22:28:28 +00006590 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006591 if (lhsType->isIntegerType()) {
6592 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006593 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006594 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006595
Chris Lattnera52c2f22008-01-04 23:18:45 +00006596 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00006597 }
John McCalle5255932011-01-31 22:28:28 +00006598
6599 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006600 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006601 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006602 if (lhsType == Context.BoolTy) {
6603 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006604 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006605 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006606
John McCalle5255932011-01-31 22:28:28 +00006607 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006608 if (lhsType->isIntegerType()) {
6609 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006610 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006611 }
6612
Steve Naroff7cae42b2009-07-10 23:34:53 +00006613 return Incompatible;
6614 }
Eli Friedman3360d892008-05-30 18:07:22 +00006615
John McCalle5255932011-01-31 22:28:28 +00006616 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00006617 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006618 if (Context.typesAreCompatible(lhsType, rhsType)) {
6619 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00006620 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006621 }
Bill Wendling216423b2007-05-30 06:30:29 +00006622 }
John McCalle5255932011-01-31 22:28:28 +00006623
Steve Naroff98cf3e92007-06-06 18:38:38 +00006624 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00006625}
6626
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006627/// \brief Constructs a transparent union from an expression that is
6628/// used to initialize the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00006629static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006630 QualType UnionType, FieldDecl *Field) {
6631 // Build an initializer list that designates the appropriate member
6632 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00006633 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00006634 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00006635 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006636 SourceLocation());
6637 Initializer->setType(UnionType);
6638 Initializer->setInitializedFieldInUnion(Field);
6639
6640 // Build a compound literal constructing a value of the transparent
6641 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00006642 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00006643 EResult = S.Owned(
6644 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6645 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006646}
6647
6648Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006649Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
6650 QualType FromType = rExpr.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006651
Mike Stump11289f42009-09-09 15:08:12 +00006652 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006653 // transparent_union GCC extension.
6654 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006655 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006656 return Incompatible;
6657
6658 // The field to initialize within the transparent union.
6659 RecordDecl *UD = UT->getDecl();
6660 FieldDecl *InitField = 0;
6661 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006662 for (RecordDecl::field_iterator it = UD->field_begin(),
6663 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006664 it != itend; ++it) {
6665 if (it->getType()->isPointerType()) {
6666 // If the transparent union contains a pointer type, we allow:
6667 // 1) void pointer
6668 // 2) null pointer constant
6669 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006670 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +00006671 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006672 InitField = *it;
6673 break;
6674 }
Mike Stump11289f42009-09-09 15:08:12 +00006675
John Wiegley01296292011-04-08 18:41:53 +00006676 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006677 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006678 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006679 InitField = *it;
6680 break;
6681 }
6682 }
6683
John McCall8cb679e2010-11-15 09:13:47 +00006684 CastKind Kind = CK_Invalid;
John Wiegley01296292011-04-08 18:41:53 +00006685 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006686 == Compatible) {
John Wiegley01296292011-04-08 18:41:53 +00006687 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006688 InitField = *it;
6689 break;
6690 }
6691 }
6692
6693 if (!InitField)
6694 return Incompatible;
6695
John Wiegley01296292011-04-08 18:41:53 +00006696 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006697 return Compatible;
6698}
6699
Chris Lattner9bad62c2008-01-04 18:04:52 +00006700Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006701Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00006702 if (getLangOptions().CPlusPlus) {
6703 if (!lhsType->isRecordType()) {
6704 // C++ 5.17p3: If the left operand is not of class type, the
6705 // expression is implicitly converted (C++ 4) to the
6706 // cv-unqualified type of the left operand.
John Wiegley01296292011-04-08 18:41:53 +00006707 ExprResult Res = PerformImplicitConversion(rExpr.get(),
6708 lhsType.getUnqualifiedType(),
6709 AA_Assigning);
6710 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00006711 return Incompatible;
John Wiegley01296292011-04-08 18:41:53 +00006712 rExpr = move(Res);
Chris Lattner0d5640c2009-04-12 09:02:39 +00006713 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00006714 }
6715
6716 // FIXME: Currently, we fall through and treat C++ classes like C
6717 // structures.
John McCall34376a62010-12-04 03:47:34 +00006718 }
Douglas Gregor9a657932008-10-21 23:43:52 +00006719
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006720 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6721 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00006722 if ((lhsType->isPointerType() ||
6723 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00006724 lhsType->isBlockPointerType())
John Wiegley01296292011-04-08 18:41:53 +00006725 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006726 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006727 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006728 return Compatible;
6729 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006730
Chris Lattnere6dcd502007-10-16 02:55:40 +00006731 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006732 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00006733 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00006734 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00006735 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00006736 // Suppress this for references: C++ 8.5.3p5.
John Wiegley01296292011-04-08 18:41:53 +00006737 if (!lhsType->isReferenceType()) {
6738 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
6739 if (rExpr.isInvalid())
6740 return Incompatible;
6741 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006742
John McCall8cb679e2010-11-15 09:13:47 +00006743 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006744 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00006745 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006746
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006747 // C99 6.5.16.1p2: The value of the right operand is converted to the
6748 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00006749 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6750 // so that we can use references in built-in functions even in C.
6751 // The getNonReferenceType() call makes sure that the resulting expression
6752 // does not have reference type.
John Wiegley01296292011-04-08 18:41:53 +00006753 if (result != Incompatible && rExpr.get()->getType() != lhsType)
6754 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006755 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006756}
6757
John Wiegley01296292011-04-08 18:41:53 +00006758QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006759 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley01296292011-04-08 18:41:53 +00006760 << lex.get()->getType() << rex.get()->getType()
6761 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00006762 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00006763}
6764
John Wiegley01296292011-04-08 18:41:53 +00006765QualType Sema::CheckVectorOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00006766 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006767 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00006768 QualType lhsType =
John Wiegley01296292011-04-08 18:41:53 +00006769 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattner574dee62008-07-26 22:17:49 +00006770 QualType rhsType =
John Wiegley01296292011-04-08 18:41:53 +00006771 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006772
Nate Begeman191a6b12008-07-14 18:02:46 +00006773 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006774 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00006775 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00006776
Nate Begeman191a6b12008-07-14 18:02:46 +00006777 // Handle the case of a vector & extvector type of the same size and element
6778 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006779 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00006780 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006781 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006782 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006783 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006784 if (lhsType->isExtVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00006785 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006786 return lhsType;
6787 }
6788
John Wiegley01296292011-04-08 18:41:53 +00006789 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006790 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00006791 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6792 // If we are allowing lax vector conversions, and LHS and RHS are both
6793 // vectors, the total size only needs to be the same. This is a
6794 // bitcast; no bits are changed but the result type is different.
John Wiegley01296292011-04-08 18:41:53 +00006795 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Eric Christophera613f562010-08-26 00:42:16 +00006796 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006797 }
Eric Christophera613f562010-08-26 00:42:16 +00006798 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006799 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006800 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006801
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006802 // Handle the case of equivalent AltiVec and GCC vector types
6803 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6804 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John Wiegley01296292011-04-08 18:41:53 +00006805 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006806 return rhsType;
6807 }
6808
Nate Begemanbd956c42009-06-28 02:36:38 +00006809 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6810 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6811 bool swapped = false;
6812 if (rhsType->isExtVectorType()) {
6813 swapped = true;
6814 std::swap(rex, lex);
6815 std::swap(rhsType, lhsType);
6816 }
Mike Stump11289f42009-09-09 15:08:12 +00006817
Nate Begeman886448d2009-06-28 19:12:57 +00006818 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00006819 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006820 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00006821 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00006822 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6823 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00006824 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00006825 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00006826 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006827 if (swapped) std::swap(rex, lex);
6828 return lhsType;
6829 }
6830 }
6831 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6832 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00006833 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6834 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00006835 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00006836 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00006837 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006838 if (swapped) std::swap(rex, lex);
6839 return lhsType;
6840 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006841 }
6842 }
Mike Stump11289f42009-09-09 15:08:12 +00006843
Nate Begeman886448d2009-06-28 19:12:57 +00006844 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00006845 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley01296292011-04-08 18:41:53 +00006846 << lex.get()->getType() << rex.get()->getType()
6847 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006848 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006849}
6850
Chris Lattnerfaa54172010-01-12 21:23:57 +00006851QualType Sema::CheckMultiplyDivideOperands(
John Wiegley01296292011-04-08 18:41:53 +00006852 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
6853 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006854 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006855
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006856 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00006857 if (lex.isInvalid() || rex.isInvalid())
6858 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006859
John Wiegley01296292011-04-08 18:41:53 +00006860 if (!lex.get()->getType()->isArithmeticType() ||
6861 !rex.get()->getType()->isArithmeticType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00006862 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006863
Chris Lattnerfaa54172010-01-12 21:23:57 +00006864 // Check for division by zero.
6865 if (isDiv &&
John Wiegley01296292011-04-08 18:41:53 +00006866 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6867 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
6868 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006869
Chris Lattnerfaa54172010-01-12 21:23:57 +00006870 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006871}
6872
Chris Lattnerfaa54172010-01-12 21:23:57 +00006873QualType Sema::CheckRemainderOperands(
John Wiegley01296292011-04-08 18:41:53 +00006874 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
6875 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6876 if (lex.get()->getType()->hasIntegerRepresentation() &&
6877 rex.get()->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006878 return CheckVectorOperands(Loc, lex, rex);
6879 return InvalidOperands(Loc, lex, rex);
6880 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006881
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006882 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00006883 if (lex.isInvalid() || rex.isInvalid())
6884 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006885
John Wiegley01296292011-04-08 18:41:53 +00006886 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00006887 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006888
Chris Lattnerfaa54172010-01-12 21:23:57 +00006889 // Check for remainder by zero.
John Wiegley01296292011-04-08 18:41:53 +00006890 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6891 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
6892 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006893
Chris Lattnerfaa54172010-01-12 21:23:57 +00006894 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006895}
6896
Chris Lattnerfaa54172010-01-12 21:23:57 +00006897QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00006898 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
6899 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006900 QualType compType = CheckVectorOperands(Loc, lex, rex);
6901 if (CompLHSTy) *CompLHSTy = compType;
6902 return compType;
6903 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006904
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006905 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00006906 if (lex.isInvalid() || rex.isInvalid())
6907 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006908
Steve Naroffe4718892007-04-27 18:30:00 +00006909 // handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00006910 if (lex.get()->getType()->isArithmeticType() &&
6911 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006912 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006913 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006914 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006915
Eli Friedman8e122982008-05-18 18:08:51 +00006916 // Put any potential pointer into PExp
John Wiegley01296292011-04-08 18:41:53 +00006917 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006918 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006919 std::swap(PExp, IExp);
6920
Steve Naroff6b712a72009-07-14 18:25:06 +00006921 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006922
Eli Friedman8e122982008-05-18 18:08:51 +00006923 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006924 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006925
Chris Lattner12bdebb2009-04-24 23:50:08 +00006926 // Check for arithmetic on pointers to incomplete types.
6927 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006928 if (getLangOptions().CPlusPlus) {
6929 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00006930 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00006931 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006932 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006933
6934 // GNU extension: arithmetic on pointer to void
6935 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00006936 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006937 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006938 if (getLangOptions().CPlusPlus) {
6939 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00006940 << lex.get()->getType() << lex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006941 return QualType();
6942 }
6943
6944 // GNU extension: arithmetic on pointer to function
6945 Diag(Loc, diag::ext_gnu_ptr_func_arith)
John Wiegley01296292011-04-08 18:41:53 +00006946 << lex.get()->getType() << lex.get()->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00006947 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006948 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00006949 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00006950 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006951 PExp->getType()->isObjCObjectPointerType()) &&
6952 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00006953 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6954 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006955 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006956 return QualType();
6957 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00006958 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006959 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006960 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6961 << PointeeTy << PExp->getSourceRange();
6962 return QualType();
6963 }
Mike Stump11289f42009-09-09 15:08:12 +00006964
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006965 if (CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00006966 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman629ffb92009-08-20 04:21:42 +00006967 if (LHSTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00006968 LHSTy = lex.get()->getType();
Eli Friedman629ffb92009-08-20 04:21:42 +00006969 if (LHSTy->isPromotableIntegerType())
6970 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006971 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006972 *CompLHSTy = LHSTy;
6973 }
Eli Friedman8e122982008-05-18 18:08:51 +00006974 return PExp->getType();
6975 }
6976 }
6977
Chris Lattner326f7572008-11-18 01:30:42 +00006978 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006979}
6980
Chris Lattner2a3569b2008-04-07 05:30:13 +00006981// C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00006982QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006983 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00006984 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006985 QualType compType = CheckVectorOperands(Loc, lex, rex);
6986 if (CompLHSTy) *CompLHSTy = compType;
6987 return compType;
6988 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006989
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006990 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00006991 if (lex.isInvalid() || rex.isInvalid())
6992 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006993
Chris Lattner4d62f422007-12-09 21:53:25 +00006994 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006995
Chris Lattner4d62f422007-12-09 21:53:25 +00006996 // Handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00006997 if (lex.get()->getType()->isArithmeticType() &&
6998 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006999 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007000 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007001 }
Mike Stump11289f42009-09-09 15:08:12 +00007002
Chris Lattner4d62f422007-12-09 21:53:25 +00007003 // Either ptr - int or ptr - ptr.
John Wiegley01296292011-04-08 18:41:53 +00007004 if (lex.get()->getType()->isAnyPointerType()) {
7005 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007006
Douglas Gregorac1fb652009-03-24 19:52:54 +00007007 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007008
Douglas Gregorac1fb652009-03-24 19:52:54 +00007009 bool ComplainAboutVoid = false;
7010 Expr *ComplainAboutFunc = 0;
7011 if (lpointee->isVoidType()) {
7012 if (getLangOptions().CPlusPlus) {
7013 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00007014 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007015 return QualType();
7016 }
7017
7018 // GNU C extension: arithmetic on pointer to void
7019 ComplainAboutVoid = true;
7020 } else if (lpointee->isFunctionType()) {
7021 if (getLangOptions().CPlusPlus) {
7022 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00007023 << lex.get()->getType() << lex.get()->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00007024 return QualType();
7025 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00007026
7027 // GNU C extension: arithmetic on pointer to function
John Wiegley01296292011-04-08 18:41:53 +00007028 ComplainAboutFunc = lex.get();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007029 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00007030 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00007031 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley01296292011-04-08 18:41:53 +00007032 << lex.get()->getSourceRange()
7033 << lex.get()->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00007034 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00007035
Chris Lattner12bdebb2009-04-24 23:50:08 +00007036 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00007037 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00007038 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley01296292011-04-08 18:41:53 +00007039 << lpointee << lex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00007040 return QualType();
7041 }
Mike Stump11289f42009-09-09 15:08:12 +00007042
Chris Lattner4d62f422007-12-09 21:53:25 +00007043 // The result type of a pointer-int computation is the pointer type.
John Wiegley01296292011-04-08 18:41:53 +00007044 if (rex.get()->getType()->isIntegerType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00007045 if (ComplainAboutVoid)
7046 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00007047 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007048 if (ComplainAboutFunc)
7049 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00007050 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00007051 << ComplainAboutFunc->getSourceRange();
7052
John Wiegley01296292011-04-08 18:41:53 +00007053 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
7054 return lex.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007055 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007056
Chris Lattner4d62f422007-12-09 21:53:25 +00007057 // Handle pointer-pointer subtractions.
John Wiegley01296292011-04-08 18:41:53 +00007058 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00007059 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007060
Douglas Gregorac1fb652009-03-24 19:52:54 +00007061 // RHS must be a completely-type object type.
7062 // Handle the GNU void* extension.
7063 if (rpointee->isVoidType()) {
7064 if (getLangOptions().CPlusPlus) {
7065 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00007066 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007067 return QualType();
7068 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007069
Douglas Gregorac1fb652009-03-24 19:52:54 +00007070 ComplainAboutVoid = true;
7071 } else if (rpointee->isFunctionType()) {
7072 if (getLangOptions().CPlusPlus) {
7073 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00007074 << rex.get()->getType() << rex.get()->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00007075 return QualType();
7076 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00007077
7078 // GNU extension: arithmetic on pointer to function
7079 if (!ComplainAboutFunc)
John Wiegley01296292011-04-08 18:41:53 +00007080 ComplainAboutFunc = rex.get();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007081 } else if (!rpointee->isDependentType() &&
7082 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00007083 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley01296292011-04-08 18:41:53 +00007084 << rex.get()->getSourceRange()
7085 << rex.get()->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00007086 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007087
Eli Friedman168fe152009-05-16 13:54:38 +00007088 if (getLangOptions().CPlusPlus) {
7089 // Pointee types must be the same: C++ [expr.add]
7090 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7091 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00007092 << lex.get()->getType() << rex.get()->getType()
7093 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00007094 return QualType();
7095 }
7096 } else {
7097 // Pointee types must be compatible C99 6.5.6p3
7098 if (!Context.typesAreCompatible(
7099 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7100 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7101 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00007102 << lex.get()->getType() << rex.get()->getType()
7103 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00007104 return QualType();
7105 }
Chris Lattner4d62f422007-12-09 21:53:25 +00007106 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007107
Douglas Gregorac1fb652009-03-24 19:52:54 +00007108 if (ComplainAboutVoid)
7109 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00007110 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007111 if (ComplainAboutFunc)
7112 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00007113 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00007114 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007115
John Wiegley01296292011-04-08 18:41:53 +00007116 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00007117 return Context.getPointerDiffType();
7118 }
7119 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007120
Chris Lattner326f7572008-11-18 01:30:42 +00007121 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007122}
7123
Douglas Gregor0bf31402010-10-08 23:50:27 +00007124static bool isScopedEnumerationType(QualType T) {
7125 if (const EnumType *ET = dyn_cast<EnumType>(T))
7126 return ET->getDecl()->isScoped();
7127 return false;
7128}
7129
John Wiegley01296292011-04-08 18:41:53 +00007130static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007131 SourceLocation Loc, unsigned Opc,
7132 QualType LHSTy) {
7133 llvm::APSInt Right;
7134 // Check right/shifter operand
John Wiegley01296292011-04-08 18:41:53 +00007135 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007136 return;
7137
7138 if (Right.isNegative()) {
John Wiegley01296292011-04-08 18:41:53 +00007139 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00007140 S.PDiag(diag::warn_shift_negative)
John Wiegley01296292011-04-08 18:41:53 +00007141 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007142 return;
7143 }
7144 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley01296292011-04-08 18:41:53 +00007145 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007146 if (Right.uge(LeftBits)) {
John Wiegley01296292011-04-08 18:41:53 +00007147 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00007148 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley01296292011-04-08 18:41:53 +00007149 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007150 return;
7151 }
7152 if (Opc != BO_Shl)
7153 return;
7154
7155 // When left shifting an ICE which is signed, we can check for overflow which
7156 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7157 // integers have defined behavior modulo one more than the maximum value
7158 // representable in the result type, so never warn for those.
7159 llvm::APSInt Left;
John Wiegley01296292011-04-08 18:41:53 +00007160 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007161 LHSTy->hasUnsignedIntegerRepresentation())
7162 return;
7163 llvm::APInt ResultBits =
7164 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7165 if (LeftBits.uge(ResultBits))
7166 return;
7167 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7168 Result = Result.shl(Right);
7169
7170 // If we are only missing a sign bit, this is less likely to result in actual
7171 // bugs -- if the result is cast back to an unsigned type, it will have the
7172 // expected value. Thus we place this behind a different warning that can be
7173 // turned off separately if needed.
7174 if (LeftBits == ResultBits - 1) {
7175 S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
7176 << Result.toString(10) << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00007177 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007178 return;
7179 }
7180
7181 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7182 << Result.toString(10) << Result.getMinSignedBits() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00007183 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007184}
7185
Chris Lattner2a3569b2008-04-07 05:30:13 +00007186// C99 6.5.7
John Wiegley01296292011-04-08 18:41:53 +00007187QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007188 unsigned Opc, bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00007189 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley01296292011-04-08 18:41:53 +00007190 if (!lex.get()->getType()->hasIntegerRepresentation() ||
7191 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00007192 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007193
Douglas Gregor0bf31402010-10-08 23:50:27 +00007194 // C++0x: Don't allow scoped enums. FIXME: Use something better than
7195 // hasIntegerRepresentation() above instead of this.
John Wiegley01296292011-04-08 18:41:53 +00007196 if (isScopedEnumerationType(lex.get()->getType()) ||
7197 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00007198 return InvalidOperands(Loc, lex, rex);
7199 }
7200
Nate Begemane46ee9a2009-10-25 02:26:48 +00007201 // Vector shifts promote their scalar inputs to vector type.
John Wiegley01296292011-04-08 18:41:53 +00007202 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Nate Begemane46ee9a2009-10-25 02:26:48 +00007203 return CheckVectorOperands(Loc, lex, rex);
7204
Chris Lattner5c11c412007-12-12 05:47:28 +00007205 // Shifts don't perform usual arithmetic conversions, they just do integer
7206 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007207
John McCall57cdd882010-12-16 19:28:59 +00007208 // For the LHS, do usual unary conversions, but then reset them away
7209 // if this is a compound assignment.
John Wiegley01296292011-04-08 18:41:53 +00007210 ExprResult old_lex = lex;
7211 lex = UsualUnaryConversions(lex.take());
7212 if (lex.isInvalid())
7213 return QualType();
7214 QualType LHSTy = lex.get()->getType();
John McCall57cdd882010-12-16 19:28:59 +00007215 if (isCompAssign) lex = old_lex;
7216
7217 // The RHS is simpler.
John Wiegley01296292011-04-08 18:41:53 +00007218 rex = UsualUnaryConversions(rex.take());
7219 if (rex.isInvalid())
7220 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007221
Ryan Flynnf53fab82009-08-07 16:20:20 +00007222 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007223 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00007224
Chris Lattner5c11c412007-12-12 05:47:28 +00007225 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007226 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00007227}
7228
Chandler Carruth17773fc2010-07-10 12:30:03 +00007229static bool IsWithinTemplateSpecialization(Decl *D) {
7230 if (DeclContext *DC = D->getDeclContext()) {
7231 if (isa<ClassTemplateSpecializationDecl>(DC))
7232 return true;
7233 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7234 return FD->isFunctionTemplateSpecialization();
7235 }
7236 return false;
7237}
7238
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007239// C99 6.5.8, C++ [expr.rel]
John Wiegley01296292011-04-08 18:41:53 +00007240QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007241 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00007242 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007243
Chris Lattner9a152e22009-12-05 05:40:13 +00007244 // Handle vector comparisons separately.
John Wiegley01296292011-04-08 18:41:53 +00007245 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00007246 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007247
John Wiegley01296292011-04-08 18:41:53 +00007248 QualType lType = lex.get()->getType();
7249 QualType rType = rex.get()->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00007250
John Wiegley01296292011-04-08 18:41:53 +00007251 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
7252 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00007253 QualType LHSStrippedType = LHSStripped->getType();
7254 QualType RHSStrippedType = RHSStripped->getType();
7255
Douglas Gregor1beec452011-03-12 01:48:56 +00007256
7257
Chandler Carruth712563b2011-02-17 08:37:06 +00007258 // Two different enums will raise a warning when compared.
7259 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
7260 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
7261 if (LHSEnumType->getDecl()->getIdentifier() &&
7262 RHSEnumType->getDecl()->getIdentifier() &&
7263 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
7264 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7265 << LHSStrippedType << RHSStrippedType
John Wiegley01296292011-04-08 18:41:53 +00007266 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth712563b2011-02-17 08:37:06 +00007267 }
7268 }
7269 }
7270
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007271 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00007272 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley01296292011-04-08 18:41:53 +00007273 !lex.get()->getLocStart().isMacroID() &&
7274 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00007275 // For non-floating point types, check for self-comparisons of the form
7276 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7277 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00007278 //
7279 // NOTE: Don't warn about comparison expressions resulting from macro
7280 // expansion. Also don't warn about comparisons which are only self
7281 // comparisons within a template specialization. The warnings should catch
7282 // obvious cases in the definition of the template anyways. The idea is to
7283 // warn when the typed comparison operator will always evaluate to the same
7284 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00007285 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00007286 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00007287 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00007288 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00007289 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00007290 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00007291 << (Opc == BO_EQ
7292 || Opc == BO_LE
7293 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00007294 } else if (lType->isArrayType() && rType->isArrayType() &&
7295 !DRL->getDecl()->getType()->isReferenceType() &&
7296 !DRR->getDecl()->getType()->isReferenceType()) {
7297 // what is it always going to eval to?
7298 char always_evals_to;
7299 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00007300 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007301 always_evals_to = 0; // false
7302 break;
John McCalle3027922010-08-25 11:45:40 +00007303 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007304 always_evals_to = 1; // true
7305 break;
7306 default:
7307 // best we can say is 'a constant'
7308 always_evals_to = 2; // e.g. array1 <= array2
7309 break;
7310 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00007311 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00007312 << 1 // array
7313 << always_evals_to);
7314 }
7315 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00007316 }
Mike Stump11289f42009-09-09 15:08:12 +00007317
Chris Lattner222b8bd2009-03-08 19:39:53 +00007318 if (isa<CastExpr>(LHSStripped))
7319 LHSStripped = LHSStripped->IgnoreParenCasts();
7320 if (isa<CastExpr>(RHSStripped))
7321 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00007322
Chris Lattner222b8bd2009-03-08 19:39:53 +00007323 // Warn about comparisons against a string constant (unless the other
7324 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007325 Expr *literalString = 0;
7326 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00007327 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007328 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007329 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00007330 literalString = lex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007331 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00007332 } else if ((isa<StringLiteral>(RHSStripped) ||
7333 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007334 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007335 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00007336 literalString = rex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007337 literalStringStripped = RHSStripped;
7338 }
7339
7340 if (literalString) {
7341 std::string resultComparison;
7342 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007343 case BO_LT: resultComparison = ") < 0"; break;
7344 case BO_GT: resultComparison = ") > 0"; break;
7345 case BO_LE: resultComparison = ") <= 0"; break;
7346 case BO_GE: resultComparison = ") >= 0"; break;
7347 case BO_EQ: resultComparison = ") == 0"; break;
7348 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007349 default: assert(false && "Invalid comparison operator");
7350 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007351
Ted Kremenek3427fac2011-02-23 01:52:04 +00007352 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00007353 PDiag(diag::warn_stringcompare)
7354 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00007355 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007356 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00007357 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007358
Douglas Gregorec170db2010-06-08 19:50:34 +00007359 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley01296292011-04-08 18:41:53 +00007360 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregorec170db2010-06-08 19:50:34 +00007361 UsualArithmeticConversions(lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00007362 if (lex.isInvalid() || rex.isInvalid())
7363 return QualType();
7364 }
Douglas Gregorec170db2010-06-08 19:50:34 +00007365 else {
John Wiegley01296292011-04-08 18:41:53 +00007366 lex = UsualUnaryConversions(lex.take());
7367 if (lex.isInvalid())
7368 return QualType();
7369
7370 rex = UsualUnaryConversions(rex.take());
7371 if (rex.isInvalid())
7372 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007373 }
7374
John Wiegley01296292011-04-08 18:41:53 +00007375 lType = lex.get()->getType();
7376 rType = rex.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007377
Douglas Gregorca63811b2008-11-19 03:25:36 +00007378 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007379 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00007380
Chris Lattnerb620c342007-08-26 01:18:55 +00007381 if (isRelational) {
7382 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007383 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007384 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00007385 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007386 if (lType->hasFloatingRepresentation())
John Wiegley01296292011-04-08 18:41:53 +00007387 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007388
Chris Lattnerb620c342007-08-26 01:18:55 +00007389 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007390 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007391 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007392
John Wiegley01296292011-04-08 18:41:53 +00007393 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007394 Expr::NPC_ValueDependentIsNull);
John Wiegley01296292011-04-08 18:41:53 +00007395 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007396 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007397
Douglas Gregorf267edd2010-06-15 21:38:40 +00007398 // All of the following pointer-related warnings are GCC extensions, except
7399 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00007400 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00007401 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007402 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00007403 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007404 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007405
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007406 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00007407 if (LCanPointeeTy == RCanPointeeTy)
7408 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007409 if (!isRelational &&
7410 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7411 // Valid unless comparison between non-null pointer and function pointer
7412 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00007413 // In a SFINAE context, we treat this as a hard error to maintain
7414 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007415 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7416 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007417 Diag(Loc,
7418 isSFINAEContext()?
7419 diag::err_typecheck_comparison_of_fptr_to_void
7420 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00007421 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007422
7423 if (isSFINAEContext())
7424 return QualType();
7425
John Wiegley01296292011-04-08 18:41:53 +00007426 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007427 return ResultTy;
7428 }
7429 }
Anders Carlssona95069c2010-11-04 03:17:43 +00007430
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007431 // C++ [expr.rel]p2:
7432 // [...] Pointer conversions (4.10) and qualification
7433 // conversions (4.4) are performed on pointer operands (or on
7434 // a pointer operand and a null pointer constant) to bring
7435 // them to their composite pointer type. [...]
7436 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007437 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007438 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007439 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007440 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007441 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007442 if (T.isNull()) {
7443 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007444 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007445 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007446 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007447 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007448 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007449 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00007450 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007451 }
7452
John Wiegley01296292011-04-08 18:41:53 +00007453 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7454 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007455 return ResultTy;
7456 }
Eli Friedman16c209612009-08-23 00:27:47 +00007457 // C99 6.5.9p2 and C99 6.5.8p2
7458 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7459 RCanPointeeTy.getUnqualifiedType())) {
7460 // Valid unless a relational comparison of function pointers
7461 if (isRelational && LCanPointeeTy->isFunctionType()) {
7462 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007463 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007464 }
7465 } else if (!isRelational &&
7466 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7467 // Valid unless comparison between non-null pointer and function pointer
7468 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7469 && !LHSIsNull && !RHSIsNull) {
7470 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00007471 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007472 }
7473 } else {
7474 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00007475 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007476 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00007477 }
John McCall7684dde2011-03-11 04:25:25 +00007478 if (LCanPointeeTy != RCanPointeeTy) {
7479 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007480 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007481 else
John Wiegley01296292011-04-08 18:41:53 +00007482 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007483 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007484 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007485 }
Mike Stump11289f42009-09-09 15:08:12 +00007486
Sebastian Redl576fd422009-05-10 18:38:11 +00007487 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007488 // Comparison of nullptr_t with itself.
7489 if (lType->isNullPtrType() && rType->isNullPtrType())
7490 return ResultTy;
7491
Mike Stump11289f42009-09-09 15:08:12 +00007492 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007493 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007494 if (RHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00007495 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007496 (!isRelational && lType->isMemberPointerType()))) {
John Wiegley01296292011-04-08 18:41:53 +00007497 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00007498 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007499 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007500 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007501 return ResultTy;
7502 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007503 if (LHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00007504 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007505 (!isRelational && rType->isMemberPointerType()))) {
John Wiegley01296292011-04-08 18:41:53 +00007506 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00007507 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007508 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007509 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007510 return ResultTy;
7511 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007512
7513 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00007514 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007515 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7516 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00007517 // In addition, pointers to members can be compared, or a pointer to
7518 // member and a null pointer constant. Pointer to member conversions
7519 // (4.11) and qualification conversions (4.4) are performed to bring
7520 // them to a common type. If one operand is a null pointer constant,
7521 // the common type is the type of the other operand. Otherwise, the
7522 // common type is a pointer to member type similar (4.4) to the type
7523 // of one of the operands, with a cv-qualification signature (4.4)
7524 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007525 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007526 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007527 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007528 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007529 if (T.isNull()) {
7530 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007531 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007532 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007533 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007534 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007535 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007536 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00007537 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007538 }
Mike Stump11289f42009-09-09 15:08:12 +00007539
John Wiegley01296292011-04-08 18:41:53 +00007540 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7541 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007542 return ResultTy;
7543 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007544
7545 // Handle scoped enumeration types specifically, since they don't promote
7546 // to integers.
John Wiegley01296292011-04-08 18:41:53 +00007547 if (lex.get()->getType()->isEnumeralType() &&
7548 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007549 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007550 }
Mike Stump11289f42009-09-09 15:08:12 +00007551
Steve Naroff081c7422008-09-04 15:10:53 +00007552 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00007553 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007554 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7555 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007556
Steve Naroff081c7422008-09-04 15:10:53 +00007557 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007558 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007559 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00007560 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007561 }
John Wiegley01296292011-04-08 18:41:53 +00007562 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007563 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007564 }
John Wiegley01296292011-04-08 18:41:53 +00007565
Steve Naroffe18f94c2008-09-28 01:11:11 +00007566 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00007567 if (!isRelational
7568 && ((lType->isBlockPointerType() && rType->isPointerType())
7569 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007570 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00007571 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007572 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00007573 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007574 ->getPointeeType()->isVoidType())))
7575 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00007576 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007577 }
John McCall7684dde2011-03-11 04:25:25 +00007578 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007579 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007580 else
John Wiegley01296292011-04-08 18:41:53 +00007581 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007582 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007583 }
Steve Naroff081c7422008-09-04 15:10:53 +00007584
John McCall7684dde2011-03-11 04:25:25 +00007585 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7586 const PointerType *LPT = lType->getAs<PointerType>();
7587 const PointerType *RPT = rType->getAs<PointerType>();
7588 if (LPT || RPT) {
7589 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7590 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007591
Steve Naroff753567f2008-11-17 19:49:16 +00007592 if (!LPtrToVoid && !RPtrToVoid &&
7593 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007594 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007595 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007596 }
John McCall7684dde2011-03-11 04:25:25 +00007597 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007598 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007599 else
John Wiegley01296292011-04-08 18:41:53 +00007600 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007601 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007602 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007603 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007604 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007605 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007606 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00007607 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007608 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007609 else
John Wiegley01296292011-04-08 18:41:53 +00007610 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007611 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007612 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007613 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007614 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7615 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007616 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007617 bool isError = false;
7618 if ((LHSIsNull && lType->isIntegerType()) ||
7619 (RHSIsNull && rType->isIntegerType())) {
7620 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007621 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007622 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007623 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007624 else if (getLangOptions().CPlusPlus) {
7625 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7626 isError = true;
7627 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007628 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007629
Chris Lattnerd99bd522009-08-23 00:03:44 +00007630 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007631 Diag(Loc, DiagID)
John Wiegley01296292011-04-08 18:41:53 +00007632 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007633 if (isError)
7634 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007635 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007636
7637 if (lType->isIntegerType())
John Wiegley01296292011-04-08 18:41:53 +00007638 lex = ImpCastExprToType(lex.take(), rType,
John McCalle84af4e2010-11-13 01:35:44 +00007639 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007640 else
John Wiegley01296292011-04-08 18:41:53 +00007641 rex = ImpCastExprToType(rex.take(), lType,
John McCalle84af4e2010-11-13 01:35:44 +00007642 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007643 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007644 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007645
Steve Naroff4b191572008-09-04 16:56:14 +00007646 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00007647 if (!isRelational && RHSIsNull
7648 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley01296292011-04-08 18:41:53 +00007649 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007650 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007651 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00007652 if (!isRelational && LHSIsNull
7653 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley01296292011-04-08 18:41:53 +00007654 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007655 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007656 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007657
Chris Lattner326f7572008-11-18 01:30:42 +00007658 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007659}
7660
Nate Begeman191a6b12008-07-14 18:02:46 +00007661/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007662/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007663/// like a scalar comparison, a vector comparison produces a vector of integer
7664/// types.
John Wiegley01296292011-04-08 18:41:53 +00007665QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner326f7572008-11-18 01:30:42 +00007666 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00007667 bool isRelational) {
7668 // Check to make sure we're operating on vectors of the same type and width,
7669 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00007670 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007671 if (vType.isNull())
7672 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007673
John Wiegley01296292011-04-08 18:41:53 +00007674 QualType lType = lex.get()->getType();
7675 QualType rType = rex.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007676
Anton Yartsev530deb92011-03-27 15:36:07 +00007677 // If AltiVec, the comparison results in a numeric type, i.e.
7678 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007679 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007680 return Context.getLogicalOperationType();
7681
Nate Begeman191a6b12008-07-14 18:02:46 +00007682 // For non-floating point types, check for self-comparisons of the form
7683 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7684 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007685 if (!lType->hasFloatingRepresentation()) {
John Wiegley01296292011-04-08 18:41:53 +00007686 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
7687 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007688 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007689 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007690 PDiag(diag::warn_comparison_always)
7691 << 0 // self-
7692 << 2 // "a constant"
7693 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007694 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007695
Nate Begeman191a6b12008-07-14 18:02:46 +00007696 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007697 if (!isRelational && lType->hasFloatingRepresentation()) {
7698 assert (rType->hasFloatingRepresentation());
John Wiegley01296292011-04-08 18:41:53 +00007699 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007700 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007701
Nate Begeman191a6b12008-07-14 18:02:46 +00007702 // Return the type for the comparison, which is the same as vector type for
7703 // integer vectors, or an integer type of identical size and number of
7704 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007705 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00007706 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007707
John McCall9dd450b2009-09-21 23:43:11 +00007708 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00007709 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007710 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00007711 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00007712 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007713 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7714
Mike Stump4e1f26a2009-02-19 03:04:26 +00007715 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007716 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00007717 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7718}
7719
Steve Naroff218bc2b2007-05-04 21:54:46 +00007720inline QualType Sema::CheckBitwiseOperands(
John Wiegley01296292011-04-08 18:41:53 +00007721 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
7722 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
7723 if (lex.get()->getType()->hasIntegerRepresentation() &&
7724 rex.get()->getType()->hasIntegerRepresentation())
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007725 return CheckVectorOperands(Loc, lex, rex);
7726
7727 return InvalidOperands(Loc, lex, rex);
7728 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007729
John Wiegley01296292011-04-08 18:41:53 +00007730 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
7731 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
7732 if (lexResult.isInvalid() || rexResult.isInvalid())
7733 return QualType();
7734 lex = lexResult.take();
7735 rex = rexResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007736
John Wiegley01296292011-04-08 18:41:53 +00007737 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
7738 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007739 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00007740 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007741}
7742
Steve Naroff218bc2b2007-05-04 21:54:46 +00007743inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley01296292011-04-08 18:41:53 +00007744 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00007745
7746 // Diagnose cases where the user write a logical and/or but probably meant a
7747 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7748 // is a constant.
John Wiegley01296292011-04-08 18:41:53 +00007749 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
7750 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00007751 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00007752 !Loc.isMacroID()) {
7753 // If the RHS can be constant folded, and if it constant folds to something
7754 // that isn't 0 or 1 (which indicate a potential logical operation that
7755 // happened to fold to true/false) then warn.
7756 Expr::EvalResult Result;
John Wiegley01296292011-04-08 18:41:53 +00007757 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects &&
Chris Lattner938533d2010-07-24 01:10:11 +00007758 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7759 Diag(Loc, diag::warn_logical_instead_of_bitwise)
John Wiegley01296292011-04-08 18:41:53 +00007760 << rex.get()->getSourceRange()
John McCalle3027922010-08-25 11:45:40 +00007761 << (Opc == BO_LAnd ? "&&" : "||")
7762 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00007763 }
7764 }
Chris Lattner8406c512010-07-13 19:41:32 +00007765
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007766 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007767 lex = UsualUnaryConversions(lex.take());
7768 if (lex.isInvalid())
7769 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007770
John Wiegley01296292011-04-08 18:41:53 +00007771 rex = UsualUnaryConversions(rex.take());
7772 if (rex.isInvalid())
7773 return QualType();
7774
7775 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007776 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007777
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007778 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007779 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007780
John McCall4a2429a2010-06-04 00:29:51 +00007781 // The following is safe because we only use this method for
7782 // non-overloadable operands.
7783
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007784 // C++ [expr.log.and]p1
7785 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007786 // The operands are both contextually converted to type bool.
John Wiegley01296292011-04-08 18:41:53 +00007787 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
7788 if (lexRes.isInvalid())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007789 return InvalidOperands(Loc, lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00007790 lex = move(lexRes);
7791
7792 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
7793 if (rexRes.isInvalid())
7794 return InvalidOperands(Loc, lex, rex);
7795 rex = move(rexRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007796
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007797 // C++ [expr.log.and]p2
7798 // C++ [expr.log.or]p2
7799 // The result is a bool.
7800 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007801}
7802
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007803/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7804/// is a read-only property; return true if so. A readonly property expression
7805/// depends on various declarations and thus must be treated specially.
7806///
Mike Stump11289f42009-09-09 15:08:12 +00007807static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007808 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7809 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00007810 if (PropExpr->isImplicitProperty()) return false;
7811
7812 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7813 QualType BaseType = PropExpr->isSuperReceiver() ?
7814 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007815 PropExpr->getBase()->getType();
7816
John McCallb7bd14f2010-12-02 01:19:52 +00007817 if (const ObjCObjectPointerType *OPT =
7818 BaseType->getAsObjCInterfacePointerType())
7819 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7820 if (S.isPropertyReadonly(PDecl, IFace))
7821 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007822 }
7823 return false;
7824}
7825
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007826static bool IsConstProperty(Expr *E, Sema &S) {
7827 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7828 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7829 if (PropExpr->isImplicitProperty()) return false;
7830
7831 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7832 QualType T = PDecl->getType();
7833 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00007834 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007835 CanQualType CT = S.Context.getCanonicalType(T);
7836 return CT.isConstQualified();
7837 }
7838 return false;
7839}
7840
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007841static bool IsReadonlyMessage(Expr *E, Sema &S) {
7842 if (E->getStmtClass() != Expr::MemberExprClass)
7843 return false;
7844 const MemberExpr *ME = cast<MemberExpr>(E);
7845 NamedDecl *Member = ME->getMemberDecl();
7846 if (isa<FieldDecl>(Member)) {
7847 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7848 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7849 return false;
7850 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7851 }
7852 return false;
7853}
7854
Chris Lattner30bd3272008-11-18 01:22:49 +00007855/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7856/// emit an error and return true. If so, return false.
7857static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007858 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007859 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007860 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007861 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7862 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007863 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7864 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007865 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7866 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007867 if (IsLV == Expr::MLV_Valid)
7868 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007869
Chris Lattner30bd3272008-11-18 01:22:49 +00007870 unsigned Diag = 0;
7871 bool NeedType = false;
7872 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00007873 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007874 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007875 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7876 NeedType = true;
7877 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007878 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007879 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7880 NeedType = true;
7881 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007882 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007883 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7884 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007885 case Expr::MLV_Valid:
7886 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007887 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007888 case Expr::MLV_MemberFunction:
7889 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007890 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7891 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007892 case Expr::MLV_IncompleteType:
7893 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007894 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007895 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007896 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007897 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007898 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7899 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007900 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007901 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7902 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007903 case Expr::MLV_ReadonlyProperty:
7904 Diag = diag::error_readonly_property_assignment;
7905 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007906 case Expr::MLV_NoSetterProperty:
7907 Diag = diag::error_nosetter_property_assignment;
7908 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007909 case Expr::MLV_InvalidMessageExpression:
7910 Diag = diag::error_readonly_message_assignment;
7911 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007912 case Expr::MLV_SubObjCPropertySetting:
7913 Diag = diag::error_no_subobject_property_setting;
7914 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007915 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007916
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007917 SourceRange Assign;
7918 if (Loc != OrigLoc)
7919 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007920 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007921 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007922 else
Mike Stump11289f42009-09-09 15:08:12 +00007923 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007924 return true;
7925}
7926
7927
7928
7929// C99 6.5.16.1
John Wiegley01296292011-04-08 18:41:53 +00007930QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007931 SourceLocation Loc,
7932 QualType CompoundType) {
7933 // Verify that LHS is a modifiable lvalue, and emit error if not.
7934 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007935 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007936
7937 QualType LHSType = LHS->getType();
John Wiegley01296292011-04-08 18:41:53 +00007938 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007939 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007940 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007941 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007942 // Simple assignment "x = y".
John Wiegley01296292011-04-08 18:41:53 +00007943 if (LHS->getObjectKind() == OK_ObjCProperty) {
7944 ExprResult LHSResult = Owned(LHS);
7945 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7946 if (LHSResult.isInvalid())
7947 return QualType();
7948 LHS = LHSResult.take();
7949 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007950 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007951 if (RHS.isInvalid())
7952 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007953 // Special case of NSObject attributes on c-style pointer types.
7954 if (ConvTy == IncompatiblePointer &&
7955 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007956 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007957 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007958 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007959 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007960
John McCall7decc9e2010-11-18 06:31:45 +00007961 if (ConvTy == Compatible &&
7962 getLangOptions().ObjCNonFragileABI &&
7963 LHSType->isObjCObjectType())
7964 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7965 << LHSType;
7966
Chris Lattnerea714382008-08-21 18:04:13 +00007967 // If the RHS is a unary plus or minus, check to see if they = and + are
7968 // right next to each other. If so, the user may have typo'd "x =+ 4"
7969 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007970 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007971 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7972 RHSCheck = ICE->getSubExpr();
7973 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007974 if ((UO->getOpcode() == UO_Plus ||
7975 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007976 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007977 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00007978 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7979 // And there is a space or other character before the subexpr of the
7980 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00007981 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7982 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007983 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007984 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007985 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007986 }
Chris Lattnerea714382008-08-21 18:04:13 +00007987 }
7988 } else {
7989 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007990 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007991 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007992
Chris Lattner326f7572008-11-18 01:30:42 +00007993 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007994 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007995 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007996
Chris Lattner39561062010-07-07 06:14:23 +00007997
7998 // Check to see if the destination operand is a dereferenced null pointer. If
7999 // so, and if not volatile-qualified, this is undefined behavior that the
8000 // optimizer will delete, so warn about it. People sometimes try to use this
8001 // to get a deterministic trap and are surprised by clang's behavior. This
8002 // only handles the pattern "*null = whatever", which is a very syntactic
8003 // check.
8004 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCalle3027922010-08-25 11:45:40 +00008005 if (UO->getOpcode() == UO_Deref &&
Chris Lattner39561062010-07-07 06:14:23 +00008006 UO->getSubExpr()->IgnoreParenCasts()->
8007 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
8008 !UO->getType().isVolatileQualified()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00008009 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
8010 PDiag(diag::warn_indirection_through_null)
8011 << UO->getSubExpr()->getSourceRange());
8012 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
8013 PDiag(diag::note_indirection_through_null));
Chris Lattner39561062010-07-07 06:14:23 +00008014 }
8015
Ted Kremenek64699be2011-02-16 01:57:07 +00008016 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00008017 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremenek64699be2011-02-16 01:57:07 +00008018
Steve Naroff98cf3e92007-06-06 18:38:38 +00008019 // C99 6.5.16p3: The type of an assignment expression is the type of the
8020 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00008021 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00008022 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8023 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00008024 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00008025 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00008026 return (getLangOptions().CPlusPlus
8027 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00008028}
8029
Chris Lattner326f7572008-11-18 01:30:42 +00008030// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00008031static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00008032 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00008033 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00008034
John McCall3aef3d82011-04-10 19:13:55 +00008035 LHS = S.CheckPlaceholderExpr(LHS.take());
8036 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00008037 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00008038 return QualType();
8039
John McCall73d36182010-10-12 07:14:40 +00008040 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8041 // operands, but not unary promotions.
8042 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00008043
John McCall34376a62010-12-04 03:47:34 +00008044 // So we treat the LHS as a ignored value, and in C++ we allow the
8045 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00008046 LHS = S.IgnoredValueConversions(LHS.take());
8047 if (LHS.isInvalid())
8048 return QualType();
John McCall34376a62010-12-04 03:47:34 +00008049
8050 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00008051 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8052 if (RHS.isInvalid())
8053 return QualType();
8054 if (!RHS.get()->getType()->isVoidType())
8055 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00008056 }
Eli Friedmanba961a92009-03-23 00:24:07 +00008057
John Wiegley01296292011-04-08 18:41:53 +00008058 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00008059}
8060
Steve Naroff7a5af782007-07-13 16:58:59 +00008061/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8062/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00008063static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8064 ExprValueKind &VK,
8065 SourceLocation OpLoc,
8066 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008067 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008068 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008069
Chris Lattner6b0cf142008-11-21 07:05:48 +00008070 QualType ResType = Op->getType();
8071 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00008072
John McCall4bc41ae2010-11-18 19:01:18 +00008073 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00008074 // Decrement of bool is not allowed.
8075 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00008076 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00008077 return QualType();
8078 }
8079 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00008080 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00008081 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00008082 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00008083 } else if (ResType->isAnyPointerType()) {
8084 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00008085
Chris Lattner6b0cf142008-11-21 07:05:48 +00008086 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00008087 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008088 if (S.getLangOptions().CPlusPlus) {
8089 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00008090 << Op->getSourceRange();
8091 return QualType();
8092 }
8093
8094 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00008095 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00008096 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008097 if (S.getLangOptions().CPlusPlus) {
8098 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00008099 << Op->getType() << Op->getSourceRange();
8100 return QualType();
8101 }
8102
John McCall4bc41ae2010-11-18 19:01:18 +00008103 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008104 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00008105 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
8106 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00008107 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00008108 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00008109 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00008110 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00008111 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
8112 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00008113 << PointeeTy << Op->getSourceRange();
8114 return QualType();
8115 }
Eli Friedman090addd2010-01-03 00:20:48 +00008116 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00008117 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00008118 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008119 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008120 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008121 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008122 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008123 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8124 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00008125 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
8126 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00008127 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00008128 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00008129 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00008130 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00008131 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008132 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00008133 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00008134 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00008135 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00008136 // In C++, a prefix increment is the same type as the operand. Otherwise
8137 // (in C or with postfix), the increment is the unqualified type of the
8138 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00008139 if (isPrefix && S.getLangOptions().CPlusPlus) {
8140 VK = VK_LValue;
8141 return ResType;
8142 } else {
8143 VK = VK_RValue;
8144 return ResType.getUnqualifiedType();
8145 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00008146}
8147
John Wiegley01296292011-04-08 18:41:53 +00008148ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00008149 assert(E->getValueKind() == VK_LValue &&
8150 E->getObjectKind() == OK_ObjCProperty);
8151 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
8152
8153 ExprValueKind VK = VK_RValue;
8154 if (PRE->isImplicitProperty()) {
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00008155 if (const ObjCMethodDecl *GetterMethod =
8156 PRE->getImplicitPropertyGetter()) {
8157 QualType Result = GetterMethod->getResultType();
8158 VK = Expr::getValueKindForType(Result);
8159 }
8160 else {
8161 Diag(PRE->getLocation(), diag::err_getter_not_found)
8162 << PRE->getBase()->getType();
8163 }
John McCall34376a62010-12-04 03:47:34 +00008164 }
8165
8166 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
8167 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00008168
8169 ExprResult Result = MaybeBindToTemporary(E);
8170 if (!Result.isInvalid())
8171 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00008172
8173 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00008174}
8175
John Wiegley01296292011-04-08 18:41:53 +00008176void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
8177 assert(LHS.get()->getValueKind() == VK_LValue &&
8178 LHS.get()->getObjectKind() == OK_ObjCProperty);
8179 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00008180
John Wiegley01296292011-04-08 18:41:53 +00008181 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00008182 // If using property-dot syntax notation for assignment, and there is a
8183 // setter, RHS expression is being passed to the setter argument. So,
8184 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00008185 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00008186 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
8187 LHSTy = (*P)->getType();
8188
8189 // Otherwise, if the getter returns an l-value, just call that.
8190 } else {
John Wiegley01296292011-04-08 18:41:53 +00008191 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00008192 ExprValueKind VK = Expr::getValueKindForType(Result);
8193 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00008194 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
8195 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00008196 return;
John McCallb7bd14f2010-12-02 01:19:52 +00008197 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008198 }
John McCall34376a62010-12-04 03:47:34 +00008199 }
8200
8201 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008202 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008203 InitializedEntity::InitializeParameter(Context, LHSTy);
John Wiegley01296292011-04-08 18:41:53 +00008204 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008205 if (!ArgE.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008206 RHS = ArgE;
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008207 }
8208}
8209
8210
Anders Carlsson806700f2008-02-01 07:15:58 +00008211/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00008212/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008213/// where the declaration is needed for type checking. We only need to
8214/// handle cases when the expression references a function designator
8215/// or is an lvalue. Here are some examples:
8216/// - &(x) => x
8217/// - &*****f => f for f a function designator.
8218/// - &s.xx => s
8219/// - &s.zz[1].yy -> s, if zz is an array
8220/// - *(x + 1) -> x, if x is an array
8221/// - &"123"[2] -> 0
8222/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00008223static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008224 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00008225 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008226 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00008227 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00008228 // If this is an arrow operator, the address is an offset from
8229 // the base's value, so the object the base refers to is
8230 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008231 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00008232 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00008233 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008234 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00008235 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00008236 // FIXME: This code shouldn't be necessary! We should catch the implicit
8237 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00008238 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8239 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8240 if (ICE->getSubExpr()->getType()->isArrayType())
8241 return getPrimaryDecl(ICE->getSubExpr());
8242 }
8243 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00008244 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008245 case Stmt::UnaryOperatorClass: {
8246 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008247
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008248 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008249 case UO_Real:
8250 case UO_Imag:
8251 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008252 return getPrimaryDecl(UO->getSubExpr());
8253 default:
8254 return 0;
8255 }
8256 }
Steve Naroff47500512007-04-19 23:00:49 +00008257 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008258 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00008259 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00008260 // If the result of an implicit cast is an l-value, we care about
8261 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008262 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00008263 default:
8264 return 0;
8265 }
8266}
8267
8268/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00008269/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00008270/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008271/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00008272/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008273/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00008274/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00008275static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
8276 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00008277 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008278 return S.Context.DependentTy;
8279 if (OrigOp->getType() == S.Context.OverloadTy)
8280 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00008281 if (OrigOp->getType() == S.Context.UnknownAnyTy)
8282 return S.Context.UnknownAnyTy;
John McCall8d08b9b2010-08-27 09:08:28 +00008283
John McCall2979fe02011-04-12 00:42:48 +00008284 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00008285
John McCall8d08b9b2010-08-27 09:08:28 +00008286 // Make sure to ignore parentheses in subsequent checks
8287 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00008288
John McCall4bc41ae2010-11-18 19:01:18 +00008289 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00008290 // Implement C99-only parts of addressof rules.
8291 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00008292 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00008293 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8294 // (assuming the deref expression is valid).
8295 return uOp->getSubExpr()->getType();
8296 }
8297 // Technically, there should be a check for array subscript
8298 // expressions here, but the result of one is always an lvalue anyway.
8299 }
John McCallf3a88602011-02-03 08:15:49 +00008300 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00008301 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00008302
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008303 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00008304 bool sfinae = S.isSFINAEContext();
8305 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8306 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008307 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00008308 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008309 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00008310 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008311 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00008312 } else if (lval == Expr::LV_MemberFunction) {
8313 // If it's an instance method, make a member pointer.
8314 // The expression must have exactly the form &A::foo.
8315
8316 // If the underlying expression isn't a decl ref, give up.
8317 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008318 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008319 << OrigOp->getSourceRange();
8320 return QualType();
8321 }
8322 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8323 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8324
8325 // The id-expression was parenthesized.
8326 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00008327 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008328 << OrigOp->getSourceRange();
8329
8330 // The method was named without a qualifier.
8331 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008332 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008333 << op->getSourceRange();
8334 }
8335
John McCall4bc41ae2010-11-18 19:01:18 +00008336 return S.Context.getMemberPointerType(op->getType(),
8337 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00008338 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00008339 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008340 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00008341 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00008342 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00008343 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00008344 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00008345 return QualType();
8346 }
John McCall086a4642010-11-24 05:12:34 +00008347 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008348 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00008349 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00008350 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00008351 return QualType();
John McCall086a4642010-11-24 05:12:34 +00008352 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00008353 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00008354 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00008355 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008356 return QualType();
John McCall086a4642010-11-24 05:12:34 +00008357 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00008358 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00008359 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00008360 << "property expression" << op->getSourceRange();
8361 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008362 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00008363 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00008364 // with the register storage-class specifier.
8365 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00008366 // in C++ it is not error to take address of a register
8367 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00008368 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00008369 !S.getLangOptions().CPlusPlus) {
8370 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00008371 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00008372 return QualType();
8373 }
John McCalld14a8642009-11-21 08:51:07 +00008374 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008375 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00008376 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00008377 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008378 // Could be a pointer to member, though, if there is an explicit
8379 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00008380 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008381 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008382 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00008383 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008384 S.Diag(OpLoc,
8385 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00008386 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008387 return QualType();
8388 }
Mike Stump11289f42009-09-09 15:08:12 +00008389
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00008390 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8391 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00008392 return S.Context.getMemberPointerType(op->getType(),
8393 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00008394 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008395 }
Anders Carlsson5b535762009-05-16 21:43:42 +00008396 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00008397 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00008398 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008399
Eli Friedmance7f9002009-05-16 23:27:50 +00008400 if (lval == Expr::LV_IncompleteVoidType) {
8401 // Taking the address of a void variable is technically illegal, but we
8402 // allow it in cases which are otherwise valid.
8403 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00008404 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00008405 }
8406
Steve Naroff47500512007-04-19 23:00:49 +00008407 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00008408 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00008409 return S.Context.getObjCObjectPointerType(op->getType());
8410 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00008411}
8412
Chris Lattner9156f1b2010-07-05 19:17:26 +00008413/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00008414static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8415 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008416 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008417 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008418
John Wiegley01296292011-04-08 18:41:53 +00008419 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8420 if (ConvResult.isInvalid())
8421 return QualType();
8422 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00008423 QualType OpTy = Op->getType();
8424 QualType Result;
8425
8426 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8427 // is an incomplete type or void. It would be possible to warn about
8428 // dereferencing a void pointer, but it's completely well-defined, and such a
8429 // warning is unlikely to catch any mistakes.
8430 if (const PointerType *PT = OpTy->getAs<PointerType>())
8431 Result = PT->getPointeeType();
8432 else if (const ObjCObjectPointerType *OPT =
8433 OpTy->getAs<ObjCObjectPointerType>())
8434 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00008435 else {
John McCall3aef3d82011-04-10 19:13:55 +00008436 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008437 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008438 if (PR.take() != Op)
8439 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008440 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008441
Chris Lattner9156f1b2010-07-05 19:17:26 +00008442 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008443 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00008444 << OpTy << Op->getSourceRange();
8445 return QualType();
8446 }
John McCall4bc41ae2010-11-18 19:01:18 +00008447
8448 // Dereferences are usually l-values...
8449 VK = VK_LValue;
8450
8451 // ...except that certain expressions are never l-values in C.
8452 if (!S.getLangOptions().CPlusPlus &&
8453 IsCForbiddenLValueType(S.Context, Result))
8454 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00008455
8456 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00008457}
Steve Naroff218bc2b2007-05-04 21:54:46 +00008458
John McCalle3027922010-08-25 11:45:40 +00008459static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00008460 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008461 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008462 switch (Kind) {
8463 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00008464 case tok::periodstar: Opc = BO_PtrMemD; break;
8465 case tok::arrowstar: Opc = BO_PtrMemI; break;
8466 case tok::star: Opc = BO_Mul; break;
8467 case tok::slash: Opc = BO_Div; break;
8468 case tok::percent: Opc = BO_Rem; break;
8469 case tok::plus: Opc = BO_Add; break;
8470 case tok::minus: Opc = BO_Sub; break;
8471 case tok::lessless: Opc = BO_Shl; break;
8472 case tok::greatergreater: Opc = BO_Shr; break;
8473 case tok::lessequal: Opc = BO_LE; break;
8474 case tok::less: Opc = BO_LT; break;
8475 case tok::greaterequal: Opc = BO_GE; break;
8476 case tok::greater: Opc = BO_GT; break;
8477 case tok::exclaimequal: Opc = BO_NE; break;
8478 case tok::equalequal: Opc = BO_EQ; break;
8479 case tok::amp: Opc = BO_And; break;
8480 case tok::caret: Opc = BO_Xor; break;
8481 case tok::pipe: Opc = BO_Or; break;
8482 case tok::ampamp: Opc = BO_LAnd; break;
8483 case tok::pipepipe: Opc = BO_LOr; break;
8484 case tok::equal: Opc = BO_Assign; break;
8485 case tok::starequal: Opc = BO_MulAssign; break;
8486 case tok::slashequal: Opc = BO_DivAssign; break;
8487 case tok::percentequal: Opc = BO_RemAssign; break;
8488 case tok::plusequal: Opc = BO_AddAssign; break;
8489 case tok::minusequal: Opc = BO_SubAssign; break;
8490 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8491 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8492 case tok::ampequal: Opc = BO_AndAssign; break;
8493 case tok::caretequal: Opc = BO_XorAssign; break;
8494 case tok::pipeequal: Opc = BO_OrAssign; break;
8495 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008496 }
8497 return Opc;
8498}
8499
John McCalle3027922010-08-25 11:45:40 +00008500static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008501 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008502 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008503 switch (Kind) {
8504 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008505 case tok::plusplus: Opc = UO_PreInc; break;
8506 case tok::minusminus: Opc = UO_PreDec; break;
8507 case tok::amp: Opc = UO_AddrOf; break;
8508 case tok::star: Opc = UO_Deref; break;
8509 case tok::plus: Opc = UO_Plus; break;
8510 case tok::minus: Opc = UO_Minus; break;
8511 case tok::tilde: Opc = UO_Not; break;
8512 case tok::exclaim: Opc = UO_LNot; break;
8513 case tok::kw___real: Opc = UO_Real; break;
8514 case tok::kw___imag: Opc = UO_Imag; break;
8515 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008516 }
8517 return Opc;
8518}
8519
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008520/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8521/// This warning is only emitted for builtin assignment operations. It is also
8522/// suppressed in the event of macro expansions.
8523static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8524 SourceLocation OpLoc) {
8525 if (!S.ActiveTemplateInstantiations.empty())
8526 return;
8527 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8528 return;
8529 lhs = lhs->IgnoreParenImpCasts();
8530 rhs = rhs->IgnoreParenImpCasts();
8531 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8532 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8533 if (!LeftDeclRef || !RightDeclRef ||
8534 LeftDeclRef->getLocation().isMacroID() ||
8535 RightDeclRef->getLocation().isMacroID())
8536 return;
8537 const ValueDecl *LeftDecl =
8538 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8539 const ValueDecl *RightDecl =
8540 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8541 if (LeftDecl != RightDecl)
8542 return;
8543 if (LeftDecl->getType().isVolatileQualified())
8544 return;
8545 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8546 if (RefTy->getPointeeType().isVolatileQualified())
8547 return;
8548
8549 S.Diag(OpLoc, diag::warn_self_assignment)
8550 << LeftDeclRef->getType()
8551 << lhs->getSourceRange() << rhs->getSourceRange();
8552}
8553
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008554/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8555/// operator @p Opc at location @c TokLoc. This routine only supports
8556/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008557ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008558 BinaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008559 Expr *lhsExpr, Expr *rhsExpr) {
8560 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008561 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008562 // The following two variables are used for compound assignment operators
8563 QualType CompLHSTy; // Type of LHS after promotions for computation
8564 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008565 ExprValueKind VK = VK_RValue;
8566 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008567
Douglas Gregor1beec452011-03-12 01:48:56 +00008568 // Check if a 'foo<int>' involved in a binary op, identifies a single
8569 // function unambiguously (i.e. an lvalue ala 13.4)
8570 // But since an assignment can trigger target based overload, exclude it in
8571 // our blind search. i.e:
8572 // template<class T> void f(); template<class T, class U> void f(U);
8573 // f<int> == 0; // resolve f<int> blindly
8574 // void (*p)(int); p = f<int>; // resolve f<int> using target
8575 if (Opc != BO_Assign) {
John McCall3aef3d82011-04-10 19:13:55 +00008576 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall31996342011-04-07 08:22:57 +00008577 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008578 lhs = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00008579
John McCall3aef3d82011-04-10 19:13:55 +00008580 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall31996342011-04-07 08:22:57 +00008581 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008582 rhs = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00008583 }
8584
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008585 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008586 case BO_Assign:
John Wiegley01296292011-04-08 18:41:53 +00008587 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00008588 if (getLangOptions().CPlusPlus &&
John Wiegley01296292011-04-08 18:41:53 +00008589 lhs.get()->getObjectKind() != OK_ObjCProperty) {
8590 VK = lhs.get()->getValueKind();
8591 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008592 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008593 if (!ResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00008594 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008595 break;
John McCalle3027922010-08-25 11:45:40 +00008596 case BO_PtrMemD:
8597 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00008598 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008599 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008600 break;
John McCalle3027922010-08-25 11:45:40 +00008601 case BO_Mul:
8602 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008603 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008604 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008605 break;
John McCalle3027922010-08-25 11:45:40 +00008606 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008607 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
8608 break;
John McCalle3027922010-08-25 11:45:40 +00008609 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008610 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
8611 break;
John McCalle3027922010-08-25 11:45:40 +00008612 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008613 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
8614 break;
John McCalle3027922010-08-25 11:45:40 +00008615 case BO_Shl:
8616 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008617 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008618 break;
John McCalle3027922010-08-25 11:45:40 +00008619 case BO_LE:
8620 case BO_LT:
8621 case BO_GE:
8622 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008623 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008624 break;
John McCalle3027922010-08-25 11:45:40 +00008625 case BO_EQ:
8626 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008627 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008628 break;
John McCalle3027922010-08-25 11:45:40 +00008629 case BO_And:
8630 case BO_Xor:
8631 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008632 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8633 break;
John McCalle3027922010-08-25 11:45:40 +00008634 case BO_LAnd:
8635 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00008636 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008637 break;
John McCalle3027922010-08-25 11:45:40 +00008638 case BO_MulAssign:
8639 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008640 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008641 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008642 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008643 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8644 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008645 break;
John McCalle3027922010-08-25 11:45:40 +00008646 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008647 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
8648 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008649 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8650 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008651 break;
John McCalle3027922010-08-25 11:45:40 +00008652 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008653 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00008654 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8655 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008656 break;
John McCalle3027922010-08-25 11:45:40 +00008657 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008658 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00008659 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8660 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008661 break;
John McCalle3027922010-08-25 11:45:40 +00008662 case BO_ShlAssign:
8663 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008664 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008665 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008666 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8667 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008668 break;
John McCalle3027922010-08-25 11:45:40 +00008669 case BO_AndAssign:
8670 case BO_XorAssign:
8671 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008672 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8673 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008674 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8675 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008676 break;
John McCalle3027922010-08-25 11:45:40 +00008677 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00008678 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00008679 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
8680 VK = rhs.get()->getValueKind();
8681 OK = rhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008682 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008683 break;
8684 }
John Wiegley01296292011-04-08 18:41:53 +00008685 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008686 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008687 if (CompResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00008688 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
8689 ResultTy, VK, OK, OpLoc));
8690 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008691 VK = VK_LValue;
John Wiegley01296292011-04-08 18:41:53 +00008692 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008693 }
John Wiegley01296292011-04-08 18:41:53 +00008694 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
8695 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00008696 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008697}
8698
Sebastian Redl44615072009-10-27 12:10:02 +00008699/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8700/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008701static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8702 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008703 const PartialDiagnostic &FirstNote,
8704 SourceRange FirstParenRange,
8705 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00008706 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008707 Self.Diag(Loc, PD);
8708
8709 if (!FirstNote.getDiagID())
8710 return;
8711
8712 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8713 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8714 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008715 return;
8716 }
8717
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008718 Self.Diag(Loc, FirstNote)
8719 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00008720 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008721
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008722 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008723 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008724
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008725 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8726 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8727 // We can't display the parentheses, so just dig the
8728 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008729 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008730 return;
8731 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008732
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008733 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00008734 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8735 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008736}
8737
Sebastian Redl44615072009-10-27 12:10:02 +00008738/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8739/// operators are mixed in a way that suggests that the programmer forgot that
8740/// comparison operators have higher precedence. The most typical example of
8741/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008742static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008743 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00008744 typedef BinaryOperator BinOp;
8745 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8746 rhsopc = static_cast<BinOp::Opcode>(-1);
8747 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008748 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00008749 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008750 rhsopc = BO->getOpcode();
8751
8752 // Subs are not binary operators.
8753 if (lhsopc == -1 && rhsopc == -1)
8754 return;
8755
8756 // Bitwise operations are sometimes used as eager logical ops.
8757 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00008758 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8759 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008760 return;
8761
Sebastian Redl44615072009-10-27 12:10:02 +00008762 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008763 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008764 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008765 << SourceRange(lhs->getLocStart(), OpLoc)
8766 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00008767 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008768 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008769 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
8770 Self.PDiag(diag::note_precedence_bitwise_silence)
8771 << BinOp::getOpcodeStr(lhsopc),
8772 lhs->getSourceRange());
Sebastian Redl44615072009-10-27 12:10:02 +00008773 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008774 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008775 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008776 << SourceRange(OpLoc, rhs->getLocEnd())
8777 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00008778 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008779 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008780 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
8781 Self.PDiag(diag::note_precedence_bitwise_silence)
8782 << BinOp::getOpcodeStr(rhsopc),
8783 rhs->getSourceRange());
Sebastian Redl43028242009-10-26 15:24:15 +00008784}
8785
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008786/// \brief It accepts a '&&' expr that is inside a '||' one.
8787/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8788/// in parentheses.
8789static void
8790EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008791 BinaryOperator *Bop) {
8792 assert(Bop->getOpcode() == BO_LAnd);
8793 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008794 Self.PDiag(diag::warn_logical_and_in_logical_or)
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008795 << Bop->getSourceRange() << OpLoc,
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008796 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008797 Bop->getSourceRange(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008798 Self.PDiag(0), SourceRange());
8799}
8800
8801/// \brief Returns true if the given expression can be evaluated as a constant
8802/// 'true'.
8803static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8804 bool Res;
8805 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8806}
8807
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008808/// \brief Returns true if the given expression can be evaluated as a constant
8809/// 'false'.
8810static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8811 bool Res;
8812 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8813}
8814
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008815/// \brief Look for '&&' in the left hand of a '||' expr.
8816static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008817 Expr *OrLHS, Expr *OrRHS) {
8818 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008819 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008820 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8821 if (EvaluatesAsFalse(S, OrRHS))
8822 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008823 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8824 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8825 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8826 } else if (Bop->getOpcode() == BO_LOr) {
8827 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8828 // If it's "a || b && 1 || c" we didn't warn earlier for
8829 // "a || b && 1", but warn now.
8830 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8831 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8832 }
8833 }
8834 }
8835}
8836
8837/// \brief Look for '&&' in the right hand of a '||' expr.
8838static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008839 Expr *OrLHS, Expr *OrRHS) {
8840 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008841 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008842 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8843 if (EvaluatesAsFalse(S, OrLHS))
8844 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008845 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8846 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8847 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008848 }
8849 }
8850}
8851
Sebastian Redl43028242009-10-26 15:24:15 +00008852/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008853/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008854static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008855 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008856 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008857 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008858 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8859
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008860 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8861 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008862 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008863 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8864 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008865 }
Sebastian Redl43028242009-10-26 15:24:15 +00008866}
8867
Steve Naroff218bc2b2007-05-04 21:54:46 +00008868// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008869ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008870 tok::TokenKind Kind,
8871 Expr *lhs, Expr *rhs) {
8872 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00008873 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8874 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008875
Sebastian Redl43028242009-10-26 15:24:15 +00008876 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8877 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8878
Douglas Gregor5287f092009-11-05 00:51:44 +00008879 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8880}
8881
John McCalldadc5752010-08-24 06:29:42 +00008882ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008883 BinaryOperatorKind Opc,
8884 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00008885 if (getLangOptions().CPlusPlus) {
8886 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008887
John McCall622114c2010-12-06 05:26:58 +00008888 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8889 UseBuiltinOperator = false;
8890 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8891 UseBuiltinOperator = true;
8892 } else {
8893 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8894 !rhs->getType()->isOverloadableType();
8895 }
8896
8897 if (!UseBuiltinOperator) {
8898 // Find all of the overloaded operators visible from this
8899 // point. We perform both an operator-name lookup from the local
8900 // scope and an argument-dependent lookup based on the types of
8901 // the arguments.
8902 UnresolvedSet<16> Functions;
8903 OverloadedOperatorKind OverOp
8904 = BinaryOperator::getOverloadedOperator(Opc);
8905 if (S && OverOp != OO_None)
8906 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8907 Functions);
8908
8909 // Build the (potentially-overloaded, potentially-dependent)
8910 // binary operation.
8911 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8912 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008913 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008914
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008915 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00008916 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008917}
8918
John McCalldadc5752010-08-24 06:29:42 +00008919ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008920 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008921 Expr *InputExpr) {
8922 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008923 ExprValueKind VK = VK_RValue;
8924 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008925 QualType resultType;
8926 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008927 case UO_PreInc:
8928 case UO_PreDec:
8929 case UO_PostInc:
8930 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008931 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008932 Opc == UO_PreInc ||
8933 Opc == UO_PostInc,
8934 Opc == UO_PreInc ||
8935 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008936 break;
John McCalle3027922010-08-25 11:45:40 +00008937 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00008938 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008939 break;
John McCall31996342011-04-07 08:22:57 +00008940 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00008941 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00008942 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008943 Input = move(resolved);
8944 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8945 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008946 break;
John McCall31996342011-04-07 08:22:57 +00008947 }
John McCalle3027922010-08-25 11:45:40 +00008948 case UO_Plus:
8949 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008950 Input = UsualUnaryConversions(Input.take());
8951 if (Input.isInvalid()) return ExprError();
8952 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008953 if (resultType->isDependentType())
8954 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008955 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8956 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008957 break;
8958 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8959 resultType->isEnumeralType())
8960 break;
8961 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008962 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008963 resultType->isPointerType())
8964 break;
John McCall36226622010-10-12 02:09:17 +00008965 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008966 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008967 if (Input.isInvalid()) return ExprError();
8968 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008969 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008970
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008971 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008972 << resultType << Input.get()->getSourceRange());
8973
John McCalle3027922010-08-25 11:45:40 +00008974 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008975 Input = UsualUnaryConversions(Input.take());
8976 if (Input.isInvalid()) return ExprError();
8977 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008978 if (resultType->isDependentType())
8979 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008980 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8981 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8982 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008983 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008984 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008985 else if (resultType->hasIntegerRepresentation())
8986 break;
8987 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008988 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008989 if (Input.isInvalid()) return ExprError();
8990 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008991 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008992 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008993 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008994 }
Steve Naroff35d85152007-05-07 00:24:15 +00008995 break;
John Wiegley01296292011-04-08 18:41:53 +00008996
John McCalle3027922010-08-25 11:45:40 +00008997 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008998 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008999 Input = DefaultFunctionArrayLvalueConversion(Input.take());
9000 if (Input.isInvalid()) return ExprError();
9001 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009002 if (resultType->isDependentType())
9003 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00009004 if (resultType->isScalarType()) {
9005 // C99 6.5.3.3p1: ok, fallthrough;
9006 if (Context.getLangOptions().CPlusPlus) {
9007 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9008 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00009009 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9010 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00009011 }
John McCall36226622010-10-12 02:09:17 +00009012 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00009013 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00009014 if (Input.isInvalid()) return ExprError();
9015 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00009016 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009017 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00009018 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00009019 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00009020
Chris Lattnerbe31ed82007-06-02 19:11:33 +00009021 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009022 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00009023 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00009024 break;
John McCalle3027922010-08-25 11:45:40 +00009025 case UO_Real:
9026 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00009027 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00009028 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00009029 if (Input.isInvalid()) return ExprError();
9030 if (Input.get()->getValueKind() != VK_RValue &&
9031 Input.get()->getObjectKind() == OK_Ordinary)
9032 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00009033 break;
John McCalle3027922010-08-25 11:45:40 +00009034 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00009035 resultType = Input.get()->getType();
9036 VK = Input.get()->getValueKind();
9037 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00009038 break;
Steve Naroff35d85152007-05-07 00:24:15 +00009039 }
John Wiegley01296292011-04-08 18:41:53 +00009040 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009041 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00009042
John Wiegley01296292011-04-08 18:41:53 +00009043 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00009044 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00009045}
Chris Lattnereefa10e2007-05-28 06:56:27 +00009046
John McCalldadc5752010-08-24 06:29:42 +00009047ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00009048 UnaryOperatorKind Opc,
9049 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00009050 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00009051 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009052 // Find all of the overloaded operators visible from this
9053 // point. We perform both an operator-name lookup from the local
9054 // scope and an argument-dependent lookup based on the types of
9055 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00009056 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00009057 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00009058 if (S && OverOp != OO_None)
9059 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9060 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009061
John McCallb268a282010-08-23 23:25:46 +00009062 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009063 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009064
John McCallb268a282010-08-23 23:25:46 +00009065 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009066}
9067
Douglas Gregor5287f092009-11-05 00:51:44 +00009068// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00009069ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00009070 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00009071 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00009072}
9073
Steve Naroff66356bd2007-09-16 14:56:35 +00009074/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00009075ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00009076 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00009077 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00009078 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00009079 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009080 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00009081}
9082
John McCalldadc5752010-08-24 06:29:42 +00009083ExprResult
John McCallb268a282010-08-23 23:25:46 +00009084Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009085 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00009086 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9087 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9088
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00009089 bool isFileScope
9090 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00009091 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009092 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00009093
Chris Lattner366727f2007-07-24 16:58:17 +00009094 // FIXME: there are a variety of strange constraints to enforce here, for
9095 // example, it is not possible to goto into a stmt expression apparently.
9096 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009097
Chris Lattner366727f2007-07-24 16:58:17 +00009098 // If there are sub stmts in the compound stmt, take the type of the last one
9099 // as the type of the stmtexpr.
9100 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009101 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00009102 if (!Compound->body_empty()) {
9103 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009104 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00009105 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009106 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9107 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00009108 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009109 }
John Wiegley01296292011-04-08 18:41:53 +00009110 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00009111 // Do function/array conversion on the last expression, but not
9112 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00009113 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9114 if (LastExpr.isInvalid())
9115 return ExprError();
9116 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00009117
John Wiegley01296292011-04-08 18:41:53 +00009118 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9119 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009120 InitializedEntity::InitializeResult(LPLoc,
9121 Ty,
9122 false),
9123 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00009124 LastExpr);
9125 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009126 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009127 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009128 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00009129 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009130 else
John Wiegley01296292011-04-08 18:41:53 +00009131 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009132 StmtExprMayBindToTemp = true;
9133 }
9134 }
9135 }
Chris Lattner944d3062008-07-26 19:51:01 +00009136 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009137
Eli Friedmanba961a92009-03-23 00:24:07 +00009138 // FIXME: Check that expression type is complete/non-abstract; statement
9139 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009140 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9141 if (StmtExprMayBindToTemp)
9142 return MaybeBindToTemporary(ResStmtExpr);
9143 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00009144}
Steve Naroff78864672007-08-01 22:05:33 +00009145
John McCalldadc5752010-08-24 06:29:42 +00009146ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009147 TypeSourceInfo *TInfo,
9148 OffsetOfComponent *CompPtr,
9149 unsigned NumComponents,
9150 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009151 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009152 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009153 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00009154
Chris Lattnerf17bd422007-08-30 17:45:32 +00009155 // We must have at least one component that refers to the type, and the first
9156 // one is known to be a field designator. Verify that the ArgTy represents
9157 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009158 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00009159 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9160 << ArgTy << TypeRange);
9161
9162 // Type must be complete per C99 7.17p3 because a declaring a variable
9163 // with an incomplete type would be ill-formed.
9164 if (!Dependent
9165 && RequireCompleteType(BuiltinLoc, ArgTy,
9166 PDiag(diag::err_offsetof_incomplete_type)
9167 << TypeRange))
9168 return ExprError();
9169
Chris Lattner78502cf2007-08-31 21:49:13 +00009170 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9171 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00009172 // FIXME: This diagnostic isn't actually visible because the location is in
9173 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00009174 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00009175 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9176 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00009177
9178 bool DidWarnAboutNonPOD = false;
9179 QualType CurrentType = ArgTy;
9180 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9181 llvm::SmallVector<OffsetOfNode, 4> Comps;
9182 llvm::SmallVector<Expr*, 4> Exprs;
9183 for (unsigned i = 0; i != NumComponents; ++i) {
9184 const OffsetOfComponent &OC = CompPtr[i];
9185 if (OC.isBrackets) {
9186 // Offset of an array sub-field. TODO: Should we allow vector elements?
9187 if (!CurrentType->isDependentType()) {
9188 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9189 if(!AT)
9190 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9191 << CurrentType);
9192 CurrentType = AT->getElementType();
9193 } else
9194 CurrentType = Context.DependentTy;
9195
9196 // The expression must be an integral expression.
9197 // FIXME: An integral constant expression?
9198 Expr *Idx = static_cast<Expr*>(OC.U.E);
9199 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9200 !Idx->getType()->isIntegerType())
9201 return ExprError(Diag(Idx->getLocStart(),
9202 diag::err_typecheck_subscript_not_integer)
9203 << Idx->getSourceRange());
9204
9205 // Record this array index.
9206 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9207 Exprs.push_back(Idx);
9208 continue;
9209 }
9210
9211 // Offset of a field.
9212 if (CurrentType->isDependentType()) {
9213 // We have the offset of a field, but we can't look into the dependent
9214 // type. Just record the identifier of the field.
9215 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9216 CurrentType = Context.DependentTy;
9217 continue;
9218 }
9219
9220 // We need to have a complete type to look into.
9221 if (RequireCompleteType(OC.LocStart, CurrentType,
9222 diag::err_offsetof_incomplete_type))
9223 return ExprError();
9224
9225 // Look for the designated field.
9226 const RecordType *RC = CurrentType->getAs<RecordType>();
9227 if (!RC)
9228 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9229 << CurrentType);
9230 RecordDecl *RD = RC->getDecl();
9231
9232 // C++ [lib.support.types]p5:
9233 // The macro offsetof accepts a restricted set of type arguments in this
9234 // International Standard. type shall be a POD structure or a POD union
9235 // (clause 9).
9236 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9237 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00009238 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00009239 PDiag(diag::warn_offsetof_non_pod_type)
9240 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9241 << CurrentType))
9242 DidWarnAboutNonPOD = true;
9243 }
9244
9245 // Look for the field.
9246 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9247 LookupQualifiedName(R, RD);
9248 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009249 IndirectFieldDecl *IndirectMemberDecl = 0;
9250 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00009251 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00009252 MemberDecl = IndirectMemberDecl->getAnonField();
9253 }
9254
Douglas Gregor882211c2010-04-28 22:16:22 +00009255 if (!MemberDecl)
9256 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9257 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9258 OC.LocEnd));
9259
Douglas Gregor10982ea2010-04-28 22:36:06 +00009260 // C99 7.17p3:
9261 // (If the specified member is a bit-field, the behavior is undefined.)
9262 //
9263 // We diagnose this as an error.
9264 if (MemberDecl->getBitWidth()) {
9265 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9266 << MemberDecl->getDeclName()
9267 << SourceRange(BuiltinLoc, RParenLoc);
9268 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9269 return ExprError();
9270 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009271
9272 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009273 if (IndirectMemberDecl)
9274 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009275
Douglas Gregord1702062010-04-29 00:18:15 +00009276 // If the member was found in a base class, introduce OffsetOfNodes for
9277 // the base class indirections.
9278 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9279 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009280 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00009281 CXXBasePath &Path = Paths.front();
9282 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9283 B != BEnd; ++B)
9284 Comps.push_back(OffsetOfNode(B->Base));
9285 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009286
Francois Pichet783dd6e2010-11-21 06:08:52 +00009287 if (IndirectMemberDecl) {
9288 for (IndirectFieldDecl::chain_iterator FI =
9289 IndirectMemberDecl->chain_begin(),
9290 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9291 assert(isa<FieldDecl>(*FI));
9292 Comps.push_back(OffsetOfNode(OC.LocStart,
9293 cast<FieldDecl>(*FI), OC.LocEnd));
9294 }
9295 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00009296 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00009297
Douglas Gregor882211c2010-04-28 22:16:22 +00009298 CurrentType = MemberDecl->getType().getNonReferenceType();
9299 }
9300
9301 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9302 TInfo, Comps.data(), Comps.size(),
9303 Exprs.data(), Exprs.size(), RParenLoc));
9304}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009305
John McCalldadc5752010-08-24 06:29:42 +00009306ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00009307 SourceLocation BuiltinLoc,
9308 SourceLocation TypeLoc,
9309 ParsedType argty,
9310 OffsetOfComponent *CompPtr,
9311 unsigned NumComponents,
9312 SourceLocation RPLoc) {
9313
Douglas Gregor882211c2010-04-28 22:16:22 +00009314 TypeSourceInfo *ArgTInfo;
9315 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
9316 if (ArgTy.isNull())
9317 return ExprError();
9318
Eli Friedman06dcfd92010-08-05 10:15:45 +00009319 if (!ArgTInfo)
9320 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9321
9322 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9323 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00009324}
9325
9326
John McCalldadc5752010-08-24 06:29:42 +00009327ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009328 Expr *CondExpr,
9329 Expr *LHSExpr, Expr *RHSExpr,
9330 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00009331 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9332
John McCall7decc9e2010-11-18 06:31:45 +00009333 ExprValueKind VK = VK_RValue;
9334 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009335 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00009336 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00009337 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009338 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00009339 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009340 } else {
9341 // The conditional expression is required to be a constant expression.
9342 llvm::APSInt condEval(32);
9343 SourceLocation ExpLoc;
9344 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009345 return ExprError(Diag(ExpLoc,
9346 diag::err_typecheck_choose_expr_requires_constant)
9347 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00009348
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009349 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00009350 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9351
9352 resType = ActiveExpr->getType();
9353 ValueDependent = ActiveExpr->isValueDependent();
9354 VK = ActiveExpr->getValueKind();
9355 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009356 }
9357
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009358 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00009359 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00009360 resType->isDependentType(),
9361 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00009362}
9363
Steve Naroffc540d662008-09-03 18:15:37 +00009364//===----------------------------------------------------------------------===//
9365// Clang Extensions.
9366//===----------------------------------------------------------------------===//
9367
9368/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009369void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009370 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9371 PushBlockScope(BlockScope, Block);
9372 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009373 if (BlockScope)
9374 PushDeclContext(BlockScope, Block);
9375 else
9376 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009377}
9378
Mike Stump82f071f2009-02-04 22:31:32 +00009379void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00009380 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00009381 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009382 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009383
John McCall8cb7bdf2010-06-04 23:28:52 +00009384 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00009385 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00009386
John McCall3882ace2011-01-05 12:14:39 +00009387 // GetTypeForDeclarator always produces a function type for a block
9388 // literal signature. Furthermore, it is always a FunctionProtoType
9389 // unless the function was written with a typedef.
9390 assert(T->isFunctionType() &&
9391 "GetTypeForDeclarator made a non-function block signature");
9392
9393 // Look for an explicit signature in that function type.
9394 FunctionProtoTypeLoc ExplicitSignature;
9395
9396 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9397 if (isa<FunctionProtoTypeLoc>(tmp)) {
9398 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9399
9400 // Check whether that explicit signature was synthesized by
9401 // GetTypeForDeclarator. If so, don't save that as part of the
9402 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00009403 if (ExplicitSignature.getLocalRangeBegin() ==
9404 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00009405 // This would be much cheaper if we stored TypeLocs instead of
9406 // TypeSourceInfos.
9407 TypeLoc Result = ExplicitSignature.getResultLoc();
9408 unsigned Size = Result.getFullDataSize();
9409 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9410 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9411
9412 ExplicitSignature = FunctionProtoTypeLoc();
9413 }
John McCalla3ccba02010-06-04 11:21:44 +00009414 }
Mike Stump11289f42009-09-09 15:08:12 +00009415
John McCall3882ace2011-01-05 12:14:39 +00009416 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9417 CurBlock->FunctionType = T;
9418
9419 const FunctionType *Fn = T->getAs<FunctionType>();
9420 QualType RetTy = Fn->getResultType();
9421 bool isVariadic =
9422 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9423
John McCall8e346702010-06-04 19:02:56 +00009424 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00009425
John McCalla3ccba02010-06-04 11:21:44 +00009426 // Don't allow returning a objc interface by value.
9427 if (RetTy->isObjCObjectType()) {
9428 Diag(ParamInfo.getSourceRange().getBegin(),
9429 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9430 return;
9431 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009432
John McCalla3ccba02010-06-04 11:21:44 +00009433 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00009434 // return type. TODO: what should we do with declarators like:
9435 // ^ * { ... }
9436 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00009437 if (RetTy != Context.DependentTy)
9438 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009439
John McCalla3ccba02010-06-04 11:21:44 +00009440 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00009441 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00009442 if (ExplicitSignature) {
9443 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9444 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009445 if (Param->getIdentifier() == 0 &&
9446 !Param->isImplicit() &&
9447 !Param->isInvalidDecl() &&
9448 !getLangOptions().CPlusPlus)
9449 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00009450 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009451 }
John McCalla3ccba02010-06-04 11:21:44 +00009452
9453 // Fake up parameter variables if we have a typedef, like
9454 // ^ fntype { ... }
9455 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9456 for (FunctionProtoType::arg_type_iterator
9457 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9458 ParmVarDecl *Param =
9459 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9460 ParamInfo.getSourceRange().getBegin(),
9461 *I);
John McCall8e346702010-06-04 19:02:56 +00009462 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009463 }
Steve Naroffc540d662008-09-03 18:15:37 +00009464 }
John McCalla3ccba02010-06-04 11:21:44 +00009465
John McCall8e346702010-06-04 19:02:56 +00009466 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009467 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00009468 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00009469 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9470 CurBlock->TheDecl->param_end(),
9471 /*CheckParameterNames=*/false);
9472 }
9473
John McCalla3ccba02010-06-04 11:21:44 +00009474 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009475 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009476
John McCall8e346702010-06-04 19:02:56 +00009477 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00009478 Diag(ParamInfo.getAttributes()->getLoc(),
9479 diag::warn_attribute_sentinel_not_variadic) << 1;
9480 // FIXME: remove the attribute.
9481 }
9482
9483 // Put the parameter variables in scope. We can bail out immediately
9484 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009485 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009486 return;
9487
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009488 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009489 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9490 (*AI)->setOwningFunction(CurBlock->TheDecl);
9491
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009492 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009493 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009494 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009495
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009496 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009497 }
John McCallf7b2fb52010-01-22 00:28:27 +00009498 }
Steve Naroffc540d662008-09-03 18:15:37 +00009499}
9500
9501/// ActOnBlockError - If there is an error parsing a block, this callback
9502/// is invoked to pop the information about the block from the action impl.
9503void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00009504 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009505 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00009506 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00009507}
9508
9509/// ActOnBlockStmtExpr - This is called when the body of a block statement
9510/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009511ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009512 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009513 // If blocks are disabled, emit an error.
9514 if (!LangOpts.Blocks)
9515 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009516
Douglas Gregor9a28e842010-03-01 23:15:13 +00009517 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009518
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009519 PopDeclContext();
9520
Steve Naroffc540d662008-09-03 18:15:37 +00009521 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009522 if (!BSI->ReturnType.isNull())
9523 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009524
Mike Stump3bf1ab42009-07-28 22:04:01 +00009525 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009526 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009527
John McCallc63de662011-02-02 13:00:07 +00009528 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00009529 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
9530 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00009531
John McCall8e346702010-06-04 19:02:56 +00009532 // If the user wrote a function type in some form, try to use that.
9533 if (!BSI->FunctionType.isNull()) {
9534 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9535
9536 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9537 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9538
9539 // Turn protoless block types into nullary block types.
9540 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009541 FunctionProtoType::ExtProtoInfo EPI;
9542 EPI.ExtInfo = Ext;
9543 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009544
9545 // Otherwise, if we don't need to change anything about the function type,
9546 // preserve its sugar structure.
9547 } else if (FTy->getResultType() == RetTy &&
9548 (!NoReturn || FTy->getNoReturnAttr())) {
9549 BlockTy = BSI->FunctionType;
9550
9551 // Otherwise, make the minimal modifications to the function type.
9552 } else {
9553 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009554 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9555 EPI.TypeQuals = 0; // FIXME: silently?
9556 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009557 BlockTy = Context.getFunctionType(RetTy,
9558 FPT->arg_type_begin(),
9559 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009560 EPI);
John McCall8e346702010-06-04 19:02:56 +00009561 }
9562
9563 // If we don't have a function type, just build one from nothing.
9564 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009565 FunctionProtoType::ExtProtoInfo EPI;
Eli Friedmanc5b20b52011-04-09 08:18:08 +00009566 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, false, 0, CC_Default);
John McCalldb40c7f2010-12-14 08:05:40 +00009567 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009568 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009569
John McCall8e346702010-06-04 19:02:56 +00009570 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9571 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009572 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009573
Chris Lattner45542ea2009-04-19 05:28:12 +00009574 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00009575 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00009576 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009577
Chris Lattner60f84492011-02-17 23:58:47 +00009578 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009579
John McCallc63de662011-02-02 13:00:07 +00009580 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCall1d570a72010-08-25 05:56:39 +00009581
Ted Kremenek1767a272011-02-23 01:51:48 +00009582 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9583 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009584 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009585}
9586
John McCalldadc5752010-08-24 06:29:42 +00009587ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00009588 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009589 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009590 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009591 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00009592 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009593}
9594
John McCalldadc5752010-08-24 06:29:42 +00009595ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009596 Expr *E, TypeSourceInfo *TInfo,
9597 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009598 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009599
Eli Friedman121ba0c2008-08-09 23:32:40 +00009600 // Get the va_list type
9601 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009602 if (VaListType->isArrayType()) {
9603 // Deal with implicit array decay; for example, on x86-64,
9604 // va_list is an array, but it's supposed to decay to
9605 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009606 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009607 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009608 ExprResult Result = UsualUnaryConversions(E);
9609 if (Result.isInvalid())
9610 return ExprError();
9611 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00009612 } else {
9613 // Otherwise, the va_list argument must be an l-value because
9614 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009615 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009616 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009617 return ExprError();
9618 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009619
Douglas Gregorad3150c2009-05-19 23:10:31 +00009620 if (!E->isTypeDependent() &&
9621 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009622 return ExprError(Diag(E->getLocStart(),
9623 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009624 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009625 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009626
Eli Friedmanba961a92009-03-23 00:24:07 +00009627 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009628 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009629
Abramo Bagnara27db2392010-08-10 10:06:15 +00009630 QualType T = TInfo->getType().getNonLValueExprType(Context);
9631 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009632}
9633
John McCalldadc5752010-08-24 06:29:42 +00009634ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009635 // The type of __null will be int or long, depending on the size of
9636 // pointers on the target.
9637 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009638 unsigned pw = Context.Target.getPointerWidth(0);
9639 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009640 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009641 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009642 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009643 else if (pw == Context.Target.getLongLongWidth())
9644 Ty = Context.LongLongTy;
9645 else {
9646 assert(!"I don't know size of pointer!");
9647 Ty = Context.IntTy;
9648 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009649
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009650 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009651}
9652
Alexis Huntc46382e2010-04-28 23:02:27 +00009653static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009654 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00009655 if (!SemaRef.getLangOptions().ObjC1)
9656 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009657
Anders Carlssonace5d072009-11-10 04:46:30 +00009658 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9659 if (!PT)
9660 return;
9661
9662 // Check if the destination is of type 'id'.
9663 if (!PT->isObjCIdType()) {
9664 // Check if the destination is the 'NSString' interface.
9665 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9666 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9667 return;
9668 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009669
Anders Carlssonace5d072009-11-10 04:46:30 +00009670 // Strip off any parens and casts.
9671 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9672 if (!SL || SL->isWide())
9673 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009674
Douglas Gregora771f462010-03-31 17:46:05 +00009675 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009676}
9677
Chris Lattner9bad62c2008-01-04 18:04:52 +00009678bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9679 SourceLocation Loc,
9680 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009681 Expr *SrcExpr, AssignmentAction Action,
9682 bool *Complained) {
9683 if (Complained)
9684 *Complained = false;
9685
Chris Lattner9bad62c2008-01-04 18:04:52 +00009686 // Decode the result (notice that AST's are still created for extensions).
9687 bool isInvalid = false;
9688 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00009689 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009690
Chris Lattner9bad62c2008-01-04 18:04:52 +00009691 switch (ConvTy) {
9692 default: assert(0 && "Unknown conversion type");
9693 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009694 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009695 DiagKind = diag::ext_typecheck_convert_pointer_int;
9696 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009697 case IntToPointer:
9698 DiagKind = diag::ext_typecheck_convert_int_pointer;
9699 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009700 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009701 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009702 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9703 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009704 case IncompatiblePointerSign:
9705 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9706 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009707 case FunctionVoidPointer:
9708 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9709 break;
John McCall4fff8f62011-02-01 00:10:29 +00009710 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009711 // Perform array-to-pointer decay if necessary.
9712 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9713
John McCall4fff8f62011-02-01 00:10:29 +00009714 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9715 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9716 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9717 DiagKind = diag::err_typecheck_incompatible_address_space;
9718 break;
9719 }
9720
9721 llvm_unreachable("unknown error case for discarding qualifiers!");
9722 // fallthrough
9723 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009724 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009725 // If the qualifiers lost were because we were applying the
9726 // (deprecated) C++ conversion from a string literal to a char*
9727 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9728 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009729 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009730 // bit of refactoring (so that the second argument is an
9731 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009732 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009733 // C++ semantics.
9734 if (getLangOptions().CPlusPlus &&
9735 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9736 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009737 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9738 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009739 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009740 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009741 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009742 case IntToBlockPointer:
9743 DiagKind = diag::err_int_to_block_pointer;
9744 break;
9745 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009746 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009747 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009748 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009749 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009750 // it can give a more specific diagnostic.
9751 DiagKind = diag::warn_incompatible_qualified_id;
9752 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009753 case IncompatibleVectors:
9754 DiagKind = diag::warn_incompatible_vectors;
9755 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009756 case Incompatible:
9757 DiagKind = diag::err_typecheck_convert_incompatible;
9758 isInvalid = true;
9759 break;
9760 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009761
Douglas Gregorc68e1402010-04-09 00:35:39 +00009762 QualType FirstType, SecondType;
9763 switch (Action) {
9764 case AA_Assigning:
9765 case AA_Initializing:
9766 // The destination type comes first.
9767 FirstType = DstType;
9768 SecondType = SrcType;
9769 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009770
Douglas Gregorc68e1402010-04-09 00:35:39 +00009771 case AA_Returning:
9772 case AA_Passing:
9773 case AA_Converting:
9774 case AA_Sending:
9775 case AA_Casting:
9776 // The source type comes first.
9777 FirstType = SrcType;
9778 SecondType = DstType;
9779 break;
9780 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009781
Douglas Gregorc68e1402010-04-09 00:35:39 +00009782 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00009783 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009784 if (Complained)
9785 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009786 return isInvalid;
9787}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009788
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009789bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009790 llvm::APSInt ICEResult;
9791 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9792 if (Result)
9793 *Result = ICEResult;
9794 return false;
9795 }
9796
Anders Carlssone54e8a12008-11-30 19:50:32 +00009797 Expr::EvalResult EvalResult;
9798
Mike Stump4e1f26a2009-02-19 03:04:26 +00009799 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009800 EvalResult.HasSideEffects) {
9801 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9802
9803 if (EvalResult.Diag) {
9804 // We only show the note if it's not the usual "invalid subexpression"
9805 // or if it's actually in a subexpression.
9806 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9807 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9808 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9809 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009810
Anders Carlssone54e8a12008-11-30 19:50:32 +00009811 return true;
9812 }
9813
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009814 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9815 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009816
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009817 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009818 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9819 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009820 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009821
Anders Carlssone54e8a12008-11-30 19:50:32 +00009822 if (Result)
9823 *Result = EvalResult.Val.getInt();
9824 return false;
9825}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009826
Douglas Gregorff790f12009-11-26 00:44:06 +00009827void
Mike Stump11289f42009-09-09 15:08:12 +00009828Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009829 ExprEvalContexts.push_back(
9830 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009831}
9832
Mike Stump11289f42009-09-09 15:08:12 +00009833void
Douglas Gregorff790f12009-11-26 00:44:06 +00009834Sema::PopExpressionEvaluationContext() {
9835 // Pop the current expression evaluation context off the stack.
9836 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9837 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009838
Douglas Gregorfab31f42009-12-12 07:57:52 +00009839 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9840 if (Rec.PotentiallyReferenced) {
9841 // Mark any remaining declarations in the current position of the stack
9842 // as "referenced". If they were not meant to be referenced, semantic
9843 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009844 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009845 I = Rec.PotentiallyReferenced->begin(),
9846 IEnd = Rec.PotentiallyReferenced->end();
9847 I != IEnd; ++I)
9848 MarkDeclarationReferenced(I->first, I->second);
9849 }
9850
9851 if (Rec.PotentiallyDiagnosed) {
9852 // Emit any pending diagnostics.
9853 for (PotentiallyEmittedDiagnostics::iterator
9854 I = Rec.PotentiallyDiagnosed->begin(),
9855 IEnd = Rec.PotentiallyDiagnosed->end();
9856 I != IEnd; ++I)
9857 Diag(I->first, I->second);
9858 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009859 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009860
9861 // When are coming out of an unevaluated context, clear out any
9862 // temporaries that we may have created as part of the evaluation of
9863 // the expression in that context: they aren't relevant because they
9864 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009865 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00009866 ExprTemporaries.size() > Rec.NumTemporaries)
9867 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9868 ExprTemporaries.end());
9869
9870 // Destroy the popped expression evaluation record.
9871 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009872}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009873
9874/// \brief Note that the given declaration was referenced in the source code.
9875///
9876/// This routine should be invoke whenever a given declaration is referenced
9877/// in the source code, and where that reference occurred. If this declaration
9878/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9879/// C99 6.9p3), then the declaration will be marked as used.
9880///
9881/// \param Loc the location where the declaration was referenced.
9882///
9883/// \param D the declaration that has been referenced by the source code.
9884void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9885 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009886
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00009887 D->setReferenced();
9888
Douglas Gregorebada0772010-06-17 23:14:26 +00009889 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009890 return;
Mike Stump11289f42009-09-09 15:08:12 +00009891
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00009892 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9893 // template or not. The reason for this is that unevaluated expressions
9894 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9895 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009896 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009897 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009898 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009899 return;
9900 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009901
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009902 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9903 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009904
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009905 // Do not mark anything as "used" within a dependent context; wait for
9906 // an instantiation.
9907 if (CurContext->isDependentContext())
9908 return;
Mike Stump11289f42009-09-09 15:08:12 +00009909
Douglas Gregorff790f12009-11-26 00:44:06 +00009910 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009911 case Unevaluated:
9912 // We are in an expression that is not potentially evaluated; do nothing.
9913 return;
Mike Stump11289f42009-09-09 15:08:12 +00009914
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009915 case PotentiallyEvaluated:
9916 // We are in a potentially-evaluated expression, so this declaration is
9917 // "used"; handle this below.
9918 break;
Mike Stump11289f42009-09-09 15:08:12 +00009919
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009920 case PotentiallyPotentiallyEvaluated:
9921 // We are in an expression that may be potentially evaluated; queue this
9922 // declaration reference until we know whether the expression is
9923 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009924 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009925 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009926
9927 case PotentiallyEvaluatedIfUsed:
9928 // Referenced declarations will only be used if the construct in the
9929 // containing expression is used.
9930 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009931 }
Mike Stump11289f42009-09-09 15:08:12 +00009932
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009933 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009934 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009935 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00009936 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruthc9262402010-08-23 07:55:51 +00009937 if (Constructor->getParent()->hasTrivialConstructor())
9938 return;
9939 if (!Constructor->isUsed(false))
9940 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00009941 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00009942 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009943 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009944 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9945 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009946
Douglas Gregor88d292c2010-05-13 16:44:06 +00009947 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009948 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009949 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009950 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009951 if (Destructor->isVirtual())
9952 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009953 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9954 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9955 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009956 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00009957 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009958 } else if (MethodDecl->isVirtual())
9959 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009960 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009961 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009962 // Recursive functions should be marked when used from another function.
9963 if (CurContext == Function) return;
9964
Mike Stump11289f42009-09-09 15:08:12 +00009965 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009966 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009967 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009968 bool AlreadyInstantiated = false;
9969 if (FunctionTemplateSpecializationInfo *SpecInfo
9970 = Function->getTemplateSpecializationInfo()) {
9971 if (SpecInfo->getPointOfInstantiation().isInvalid())
9972 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009973 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009974 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009975 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009976 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009977 = Function->getMemberSpecializationInfo()) {
9978 if (MSInfo->getPointOfInstantiation().isInvalid())
9979 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009980 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009981 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009982 AlreadyInstantiated = true;
9983 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009984
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009985 if (!AlreadyInstantiated) {
9986 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9987 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9988 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9989 Loc));
9990 else
Chandler Carruth54080172010-08-25 08:44:16 +00009991 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009992 }
John McCall83779672011-02-19 02:53:41 +00009993 } else {
9994 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009995 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9996 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009997 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009998 MarkDeclarationReferenced(Loc, *i);
9999 }
John McCall83779672011-02-19 02:53:41 +000010000 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010001
John McCall83779672011-02-19 02:53:41 +000010002 // Keep track of used but undefined functions.
10003 if (!Function->isPure() && !Function->hasBody() &&
10004 Function->getLinkage() != ExternalLinkage) {
10005 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
10006 if (old.isInvalid()) old = Loc;
10007 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +000010008
John McCall83779672011-02-19 02:53:41 +000010009 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010010 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +000010011 }
Mike Stump11289f42009-09-09 15:08:12 +000010012
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010013 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +000010014 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +000010015 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +000010016 Var->getInstantiatedFromStaticDataMember()) {
10017 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10018 assert(MSInfo && "Missing member specialization information?");
10019 if (MSInfo->getPointOfInstantiation().isInvalid() &&
10020 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
10021 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth54080172010-08-25 08:44:16 +000010022 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +000010023 }
10024 }
Mike Stump11289f42009-09-09 15:08:12 +000010025
John McCall15dd4042011-02-21 19:25:48 +000010026 // Keep track of used but undefined variables. We make a hole in
10027 // the warning for static const data members with in-line
10028 // initializers.
John McCall83779672011-02-19 02:53:41 +000010029 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +000010030 && Var->getLinkage() != ExternalLinkage
10031 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +000010032 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
10033 if (old.isInvalid()) old = Loc;
10034 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +000010035
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010036 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +000010037 return;
Sam Weinigbae69142009-09-11 03:29:30 +000010038 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010039}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010040
Douglas Gregor5597ab42010-05-07 23:12:07 +000010041namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000010042 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000010043 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000010044 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000010045 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10046 Sema &S;
10047 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010048
Douglas Gregor5597ab42010-05-07 23:12:07 +000010049 public:
10050 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010051
Douglas Gregor5597ab42010-05-07 23:12:07 +000010052 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010053
10054 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10055 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010056 };
10057}
10058
Chandler Carruthaf80f662010-06-09 08:17:30 +000010059bool MarkReferencedDecls::TraverseTemplateArgument(
10060 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010061 if (Arg.getKind() == TemplateArgument::Declaration) {
10062 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
10063 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010064
10065 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010066}
10067
Chandler Carruthaf80f662010-06-09 08:17:30 +000010068bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010069 if (ClassTemplateSpecializationDecl *Spec
10070 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10071 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000010072 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000010073 }
10074
Chandler Carruthc65667c2010-06-10 10:31:57 +000010075 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000010076}
10077
10078void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10079 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000010080 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000010081}
10082
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010083namespace {
10084 /// \brief Helper class that marks all of the declarations referenced by
10085 /// potentially-evaluated subexpressions as "referenced".
10086 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10087 Sema &S;
10088
10089 public:
10090 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10091
10092 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
10093
10094 void VisitDeclRefExpr(DeclRefExpr *E) {
10095 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10096 }
10097
10098 void VisitMemberExpr(MemberExpr *E) {
10099 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010100 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010101 }
10102
10103 void VisitCXXNewExpr(CXXNewExpr *E) {
10104 if (E->getConstructor())
10105 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
10106 if (E->getOperatorNew())
10107 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
10108 if (E->getOperatorDelete())
10109 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010110 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010111 }
10112
10113 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10114 if (E->getOperatorDelete())
10115 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010116 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10117 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10118 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10119 S.MarkDeclarationReferenced(E->getLocStart(),
10120 S.LookupDestructor(Record));
10121 }
10122
Douglas Gregor32b3de52010-09-11 23:32:50 +000010123 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010124 }
10125
10126 void VisitCXXConstructExpr(CXXConstructExpr *E) {
10127 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010128 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010129 }
10130
10131 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
10132 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10133 }
Douglas Gregorf0873f42010-10-19 17:17:35 +000010134
10135 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10136 Visit(E->getExpr());
10137 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010138 };
10139}
10140
10141/// \brief Mark any declarations that appear within this expression or any
10142/// potentially-evaluated subexpressions as "referenced".
10143void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
10144 EvaluatedExprMarker(*this).Visit(E);
10145}
10146
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010147/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10148/// of the program being compiled.
10149///
10150/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010151/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010152/// possibility that the code will actually be executable. Code in sizeof()
10153/// expressions, code used only during overload resolution, etc., are not
10154/// potentially evaluated. This routine will suppress such diagnostics or,
10155/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010156/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010157/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010158///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010159/// This routine should be used for all diagnostics that describe the run-time
10160/// behavior of a program, such as passing a non-POD value through an ellipsis.
10161/// Failure to do so will likely result in spurious diagnostics or failures
10162/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +000010163bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010164 const PartialDiagnostic &PD) {
10165 switch (ExprEvalContexts.back().Context ) {
10166 case Unevaluated:
10167 // The argument will never be evaluated, so don't complain.
10168 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010169
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010170 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010171 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +000010172 if (stmt && getCurFunctionOrMethodDecl()) {
10173 FunctionScopes.back()->PossiblyUnreachableDiags.
10174 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
10175 }
10176 else
10177 Diag(Loc, PD);
10178
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010179 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010180
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010181 case PotentiallyPotentiallyEvaluated:
10182 ExprEvalContexts.back().addDiagnostic(Loc, PD);
10183 break;
10184 }
10185
10186 return false;
10187}
10188
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010189bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10190 CallExpr *CE, FunctionDecl *FD) {
10191 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10192 return false;
10193
10194 PartialDiagnostic Note =
10195 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
10196 << FD->getDeclName() : PDiag();
10197 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010198
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010199 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010200 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010201 PDiag(diag::err_call_function_incomplete_return)
10202 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010203 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010204 << CE->getSourceRange(),
10205 std::make_pair(NoteLoc, Note)))
10206 return true;
10207
10208 return false;
10209}
10210
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010211// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000010212// will prevent this condition from triggering, which is what we want.
10213void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10214 SourceLocation Loc;
10215
John McCall0506e4a2009-11-11 02:41:58 +000010216 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010217 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000010218
John McCalld5707ab2009-10-12 21:59:07 +000010219 if (isa<BinaryOperator>(E)) {
10220 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010221 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000010222 return;
10223
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010224 IsOrAssign = Op->getOpcode() == BO_OrAssign;
10225
John McCallb0e419e2009-11-12 00:06:05 +000010226 // Greylist some idioms by putting them into a warning subcategory.
10227 if (ObjCMessageExpr *ME
10228 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10229 Selector Sel = ME->getSelector();
10230
John McCallb0e419e2009-11-12 00:06:05 +000010231 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010232 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000010233 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10234
10235 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010236 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000010237 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10238 }
John McCall0506e4a2009-11-11 02:41:58 +000010239
John McCalld5707ab2009-10-12 21:59:07 +000010240 Loc = Op->getOperatorLoc();
10241 } else if (isa<CXXOperatorCallExpr>(E)) {
10242 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010243 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000010244 return;
10245
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010246 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000010247 Loc = Op->getOperatorLoc();
10248 } else {
10249 // Not an assignment.
10250 return;
10251 }
10252
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000010253 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010254
10255 if (IsOrAssign)
10256 Diag(Loc, diag::note_condition_or_assign_to_comparison)
10257 << FixItHint::CreateReplacement(Loc, "!=");
10258 else
10259 Diag(Loc, diag::note_condition_assign_to_comparison)
10260 << FixItHint::CreateReplacement(Loc, "==");
10261
Fariborz Jahaniane72509c2011-04-13 20:31:26 +000010262 SourceLocation Open = E->getSourceRange().getBegin();
Eli Friedman6620dde2011-04-14 00:51:41 +000010263 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Fariborz Jahanian38675542011-04-13 22:18:37 +000010264 Diag(Loc, diag::note_condition_assign_silence)
10265 << FixItHint::CreateInsertion(Open, "(")
Eli Friedman6620dde2011-04-14 00:51:41 +000010266 << FixItHint::CreateInsertion(Close, ")");
John McCalld5707ab2009-10-12 21:59:07 +000010267}
10268
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010269/// \brief Redundant parentheses over an equality comparison can indicate
10270/// that the user intended an assignment used as condition.
10271void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010272 // Don't warn if the parens came from a macro.
10273 SourceLocation parenLoc = parenE->getLocStart();
10274 if (parenLoc.isInvalid() || parenLoc.isMacroID())
10275 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000010276 // Don't warn for dependent expressions.
10277 if (parenE->isTypeDependent())
10278 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010279
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010280 Expr *E = parenE->IgnoreParens();
10281
10282 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000010283 if (opE->getOpcode() == BO_EQ &&
10284 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10285 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010286 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000010287
Ted Kremenekae022092011-02-02 02:20:30 +000010288 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
10289 Diag(Loc, diag::note_equality_comparison_to_assign)
10290 << FixItHint::CreateReplacement(Loc, "=");
10291 Diag(Loc, diag::note_equality_comparison_silence)
10292 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
10293 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010294 }
10295}
10296
John Wiegley01296292011-04-08 18:41:53 +000010297ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000010298 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010299 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10300 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000010301
10302 if (!E->isTypeDependent()) {
John Wiegley01296292011-04-08 18:41:53 +000010303 if (E->isBoundMemberFunction(Context)) {
10304 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000010305 << E->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +000010306 return ExprError();
10307 }
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000010308
John McCall34376a62010-12-04 03:47:34 +000010309 if (getLangOptions().CPlusPlus)
10310 return CheckCXXBooleanCondition(E); // C++ 6.4p4
10311
John Wiegley01296292011-04-08 18:41:53 +000010312 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10313 if (ERes.isInvalid())
10314 return ExprError();
10315 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000010316
10317 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000010318 if (!T->isScalarType()) { // C99 6.8.4.1p1
10319 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10320 << T << E->getSourceRange();
10321 return ExprError();
10322 }
John McCalld5707ab2009-10-12 21:59:07 +000010323 }
10324
John Wiegley01296292011-04-08 18:41:53 +000010325 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000010326}
Douglas Gregore60e41a2010-05-06 17:25:47 +000010327
John McCalldadc5752010-08-24 06:29:42 +000010328ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
10329 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +000010330 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +000010331 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010332
10333 return CheckBooleanCondition(Sub, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000010334}
John McCall36e7fe32010-10-12 00:20:44 +000010335
John McCall31996342011-04-07 08:22:57 +000010336namespace {
John McCall2979fe02011-04-12 00:42:48 +000010337 /// A visitor for rebuilding a call to an __unknown_any expression
10338 /// to have an appropriate type.
10339 struct RebuildUnknownAnyFunction
10340 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10341
10342 Sema &S;
10343
10344 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10345
10346 ExprResult VisitStmt(Stmt *S) {
10347 llvm_unreachable("unexpected statement!");
10348 return ExprError();
10349 }
10350
10351 ExprResult VisitExpr(Expr *expr) {
10352 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
10353 << expr->getSourceRange();
10354 return ExprError();
10355 }
10356
10357 /// Rebuild an expression which simply semantically wraps another
10358 /// expression which it shares the type and value kind of.
10359 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10360 ExprResult subResult = Visit(expr->getSubExpr());
10361 if (subResult.isInvalid()) return ExprError();
10362
10363 Expr *subExpr = subResult.take();
10364 expr->setSubExpr(subExpr);
10365 expr->setType(subExpr->getType());
10366 expr->setValueKind(subExpr->getValueKind());
10367 assert(expr->getObjectKind() == OK_Ordinary);
10368 return expr;
10369 }
10370
10371 ExprResult VisitParenExpr(ParenExpr *paren) {
10372 return rebuildSugarExpr(paren);
10373 }
10374
10375 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10376 return rebuildSugarExpr(op);
10377 }
10378
10379 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10380 ExprResult subResult = Visit(op->getSubExpr());
10381 if (subResult.isInvalid()) return ExprError();
10382
10383 Expr *subExpr = subResult.take();
10384 op->setSubExpr(subExpr);
10385 op->setType(S.Context.getPointerType(subExpr->getType()));
10386 assert(op->getValueKind() == VK_RValue);
10387 assert(op->getObjectKind() == OK_Ordinary);
10388 return op;
10389 }
10390
10391 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
10392 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
10393
10394 expr->setType(decl->getType());
10395
10396 assert(expr->getValueKind() == VK_RValue);
10397 if (S.getLangOptions().CPlusPlus &&
10398 !(isa<CXXMethodDecl>(decl) &&
10399 cast<CXXMethodDecl>(decl)->isInstance()))
10400 expr->setValueKind(VK_LValue);
10401
10402 return expr;
10403 }
10404
10405 ExprResult VisitMemberExpr(MemberExpr *mem) {
10406 return resolveDecl(mem, mem->getMemberDecl());
10407 }
10408
10409 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
10410 return resolveDecl(ref, ref->getDecl());
10411 }
10412 };
10413}
10414
10415/// Given a function expression of unknown-any type, try to rebuild it
10416/// to have a function type.
10417static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
10418 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
10419 if (result.isInvalid()) return ExprError();
10420 return S.DefaultFunctionArrayConversion(result.take());
10421}
10422
10423namespace {
John McCall2d2e8702011-04-11 07:02:50 +000010424 /// A visitor for rebuilding an expression of type __unknown_anytype
10425 /// into one which resolves the type directly on the referring
10426 /// expression. Strict preservation of the original source
10427 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000010428 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000010429 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000010430
10431 Sema &S;
10432
10433 /// The current destination type.
10434 QualType DestType;
10435
10436 RebuildUnknownAnyExpr(Sema &S, QualType castType)
10437 : S(S), DestType(castType) {}
10438
John McCall39439732011-04-09 22:50:59 +000010439 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000010440 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +000010441 return ExprError();
John McCall31996342011-04-07 08:22:57 +000010442 }
10443
John McCall2d2e8702011-04-11 07:02:50 +000010444 ExprResult VisitExpr(Expr *expr) {
10445 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10446 << expr->getSourceRange();
10447 return ExprError();
John McCall31996342011-04-07 08:22:57 +000010448 }
10449
John McCall2d2e8702011-04-11 07:02:50 +000010450 ExprResult VisitCallExpr(CallExpr *call);
10451 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
10452
John McCall39439732011-04-09 22:50:59 +000010453 /// Rebuild an expression which simply semantically wraps another
10454 /// expression which it shares the type and value kind of.
10455 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10456 ExprResult subResult = Visit(expr->getSubExpr());
John McCall2979fe02011-04-12 00:42:48 +000010457 if (subResult.isInvalid()) return ExprError();
John McCall39439732011-04-09 22:50:59 +000010458 Expr *subExpr = subResult.take();
10459 expr->setSubExpr(subExpr);
10460 expr->setType(subExpr->getType());
10461 expr->setValueKind(subExpr->getValueKind());
10462 assert(expr->getObjectKind() == OK_Ordinary);
10463 return expr;
10464 }
John McCall31996342011-04-07 08:22:57 +000010465
John McCall39439732011-04-09 22:50:59 +000010466 ExprResult VisitParenExpr(ParenExpr *paren) {
10467 return rebuildSugarExpr(paren);
10468 }
10469
10470 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10471 return rebuildSugarExpr(op);
10472 }
10473
John McCall2979fe02011-04-12 00:42:48 +000010474 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10475 const PointerType *ptr = DestType->getAs<PointerType>();
10476 if (!ptr) {
10477 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
10478 << op->getSourceRange();
10479 return ExprError();
10480 }
10481 assert(op->getValueKind() == VK_RValue);
10482 assert(op->getObjectKind() == OK_Ordinary);
10483 op->setType(DestType);
10484
10485 // Build the sub-expression as if it were an object of the pointee type.
10486 DestType = ptr->getPointeeType();
10487 ExprResult subResult = Visit(op->getSubExpr());
10488 if (subResult.isInvalid()) return ExprError();
10489 op->setSubExpr(subResult.take());
10490 return op;
10491 }
10492
John McCall2d2e8702011-04-11 07:02:50 +000010493 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCall39439732011-04-09 22:50:59 +000010494
John McCall2979fe02011-04-12 00:42:48 +000010495 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCall39439732011-04-09 22:50:59 +000010496
John McCall2979fe02011-04-12 00:42:48 +000010497 ExprResult VisitMemberExpr(MemberExpr *mem) {
10498 return resolveDecl(mem, mem->getMemberDecl());
10499 }
John McCall39439732011-04-09 22:50:59 +000010500
10501 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall2d2e8702011-04-11 07:02:50 +000010502 return resolveDecl(ref, ref->getDecl());
John McCall31996342011-04-07 08:22:57 +000010503 }
10504 };
10505}
10506
John McCall2d2e8702011-04-11 07:02:50 +000010507/// Rebuilds a call expression which yielded __unknown_anytype.
10508ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
10509 Expr *callee = call->getCallee();
10510
10511 enum FnKind {
10512 FK_Function,
10513 FK_FunctionPointer,
10514 FK_BlockPointer
10515 };
10516
10517 FnKind kind;
10518 QualType type = callee->getType();
10519 if (type->isFunctionType()) {
10520 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
10521 kind = FK_Function;
10522 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
10523 type = ptr->getPointeeType();
10524 kind = FK_FunctionPointer;
10525 } else {
10526 type = type->castAs<BlockPointerType>()->getPointeeType();
10527 kind = FK_BlockPointer;
10528 }
10529 const FunctionType *fnType = type->castAs<FunctionType>();
10530
10531 // Verify that this is a legal result type of a function.
10532 if (DestType->isArrayType() || DestType->isFunctionType()) {
10533 unsigned diagID = diag::err_func_returning_array_function;
10534 if (kind == FK_BlockPointer)
10535 diagID = diag::err_block_returning_array_function;
10536
10537 S.Diag(call->getExprLoc(), diagID)
10538 << DestType->isFunctionType() << DestType;
10539 return ExprError();
10540 }
10541
10542 // Otherwise, go ahead and set DestType as the call's result.
10543 call->setType(DestType.getNonLValueExprType(S.Context));
10544 call->setValueKind(Expr::getValueKindForType(DestType));
10545 assert(call->getObjectKind() == OK_Ordinary);
10546
10547 // Rebuild the function type, replacing the result type with DestType.
10548 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
10549 DestType = S.Context.getFunctionType(DestType,
10550 proto->arg_type_begin(),
10551 proto->getNumArgs(),
10552 proto->getExtProtoInfo());
10553 else
10554 DestType = S.Context.getFunctionNoProtoType(DestType,
10555 fnType->getExtInfo());
10556
10557 // Rebuild the appropriate pointer-to-function type.
10558 switch (kind) {
10559 case FK_Function:
10560 // Nothing to do.
10561 break;
10562
10563 case FK_FunctionPointer:
10564 DestType = S.Context.getPointerType(DestType);
10565 break;
10566
10567 case FK_BlockPointer:
10568 DestType = S.Context.getBlockPointerType(DestType);
10569 break;
10570 }
10571
10572 // Finally, we can recurse.
10573 ExprResult calleeResult = Visit(callee);
10574 if (!calleeResult.isUsable()) return ExprError();
10575 call->setCallee(calleeResult.take());
10576
10577 // Bind a temporary if necessary.
10578 return S.MaybeBindToTemporary(call);
10579}
10580
10581ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall2979fe02011-04-12 00:42:48 +000010582 ObjCMethodDecl *method = msg->getMethodDecl();
10583 assert(method && "__unknown_anytype message without result type?");
John McCall2d2e8702011-04-11 07:02:50 +000010584
John McCall2979fe02011-04-12 00:42:48 +000010585 // Verify that this is a legal result type of a call.
10586 if (DestType->isArrayType() || DestType->isFunctionType()) {
10587 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
10588 << DestType->isFunctionType() << DestType;
10589 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010590 }
10591
John McCall2979fe02011-04-12 00:42:48 +000010592 assert(method->getResultType() == S.Context.UnknownAnyTy);
10593 method->setResultType(DestType);
10594
John McCall2d2e8702011-04-11 07:02:50 +000010595 // Change the type of the message.
John McCall2979fe02011-04-12 00:42:48 +000010596 msg->setType(DestType.getNonReferenceType());
10597 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000010598
John McCall2979fe02011-04-12 00:42:48 +000010599 return S.MaybeBindToTemporary(msg);
John McCall2d2e8702011-04-11 07:02:50 +000010600}
10601
10602ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall2979fe02011-04-12 00:42:48 +000010603 // The only case we should ever see here is a function-to-pointer decay.
John McCall2d2e8702011-04-11 07:02:50 +000010604 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall2d2e8702011-04-11 07:02:50 +000010605 assert(ice->getValueKind() == VK_RValue);
10606 assert(ice->getObjectKind() == OK_Ordinary);
10607
John McCall2979fe02011-04-12 00:42:48 +000010608 ice->setType(DestType);
10609
John McCall2d2e8702011-04-11 07:02:50 +000010610 // Rebuild the sub-expression as the pointee (function) type.
10611 DestType = DestType->castAs<PointerType>()->getPointeeType();
10612
10613 ExprResult result = Visit(ice->getSubExpr());
10614 if (!result.isUsable()) return ExprError();
10615
10616 ice->setSubExpr(result.take());
10617 return S.Owned(ice);
10618}
10619
John McCall2979fe02011-04-12 00:42:48 +000010620ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall2d2e8702011-04-11 07:02:50 +000010621 ExprValueKind valueKind = VK_LValue;
John McCall2d2e8702011-04-11 07:02:50 +000010622 QualType type = DestType;
10623
10624 // We know how to make this work for certain kinds of decls:
10625
10626 // - functions
John McCall2979fe02011-04-12 00:42:48 +000010627 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
10628 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
John McCall2d2e8702011-04-11 07:02:50 +000010629 if (method->isInstance()) valueKind = VK_RValue;
10630
10631 // This is true because FunctionDecls must always have function
10632 // type, so we can't be resolving the entire thing at once.
10633 assert(type->isFunctionType());
10634
10635 // Function references aren't l-values in C.
10636 if (!S.getLangOptions().CPlusPlus)
10637 valueKind = VK_RValue;
10638
10639 // - variables
10640 } else if (isa<VarDecl>(decl)) {
John McCall2979fe02011-04-12 00:42:48 +000010641 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
10642 type = refTy->getPointeeType();
John McCall2d2e8702011-04-11 07:02:50 +000010643 } else if (type->isFunctionType()) {
John McCall2979fe02011-04-12 00:42:48 +000010644 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
10645 << decl << expr->getSourceRange();
10646 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010647 }
10648
10649 // - nothing else
10650 } else {
10651 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10652 << decl << expr->getSourceRange();
10653 return ExprError();
10654 }
10655
John McCall2979fe02011-04-12 00:42:48 +000010656 decl->setType(DestType);
10657 expr->setType(type);
10658 expr->setValueKind(valueKind);
10659 return S.Owned(expr);
John McCall2d2e8702011-04-11 07:02:50 +000010660}
10661
John McCall31996342011-04-07 08:22:57 +000010662/// Check a cast of an unknown-any type. We intentionally only
10663/// trigger this for C-style casts.
John Wiegley01296292011-04-08 18:41:53 +000010664ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
10665 Expr *castExpr, CastKind &castKind,
10666 ExprValueKind &VK, CXXCastPath &path) {
John McCall31996342011-04-07 08:22:57 +000010667 // Rewrite the casted expression from scratch.
John McCall39439732011-04-09 22:50:59 +000010668 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
10669 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000010670
John McCall39439732011-04-09 22:50:59 +000010671 castExpr = result.take();
10672 VK = castExpr->getValueKind();
10673 castKind = CK_NoOp;
10674
10675 return castExpr;
John McCall31996342011-04-07 08:22:57 +000010676}
10677
10678static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
10679 Expr *orig = e;
John McCall2d2e8702011-04-11 07:02:50 +000010680 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000010681 while (true) {
10682 e = e->IgnoreParenImpCasts();
John McCall2d2e8702011-04-11 07:02:50 +000010683 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall31996342011-04-07 08:22:57 +000010684 e = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000010685 diagID = diag::err_uncasted_call_of_unknown_any;
10686 } else {
John McCall31996342011-04-07 08:22:57 +000010687 break;
John McCall2d2e8702011-04-11 07:02:50 +000010688 }
John McCall31996342011-04-07 08:22:57 +000010689 }
10690
John McCall2d2e8702011-04-11 07:02:50 +000010691 SourceLocation loc;
10692 NamedDecl *d;
10693 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10694 loc = ref->getLocation();
10695 d = ref->getDecl();
10696 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
10697 loc = mem->getMemberLoc();
10698 d = mem->getMemberDecl();
10699 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
10700 diagID = diag::err_uncasted_call_of_unknown_any;
10701 loc = msg->getSelectorLoc();
10702 d = msg->getMethodDecl();
10703 assert(d && "unknown method returning __unknown_any?");
10704 } else {
10705 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10706 << e->getSourceRange();
10707 return ExprError();
10708 }
10709
10710 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000010711
10712 // Never recoverable.
10713 return ExprError();
10714}
10715
John McCall36e7fe32010-10-12 00:20:44 +000010716/// Check for operands with placeholder types and complain if found.
10717/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000010718ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +000010719 // Placeholder types are always *exactly* the appropriate builtin type.
10720 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +000010721
John McCall31996342011-04-07 08:22:57 +000010722 // Overloaded expressions.
10723 if (type == Context.OverloadTy)
10724 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010725 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +000010726 QualType(),
10727 diag::err_ovl_unresolvable);
10728
10729 // Expressions of unknown type.
10730 if (type == Context.UnknownAnyTy)
10731 return diagnoseUnknownAnyExpr(*this, E);
10732
10733 assert(!type->isPlaceholderType());
10734 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +000010735}
Richard Trieu2c850c02011-04-21 21:44:26 +000010736
10737bool Sema::CheckCaseExpression(Expr *expr) {
10738 if (expr->isTypeDependent())
10739 return true;
10740 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
10741 return expr->getType()->isIntegralOrEnumerationType();
10742 return false;
10743}