blob: 80946ead64aa53e236f3fa46ae8a190f8631f518 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/ASTContext.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000023#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000024#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000026#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000027#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000031#include "clang/Lex/LiteralSupport.h"
32#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000033#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Designator.h"
35#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000036#include "clang/Sema/ScopeInfo.h"
John McCall19510852010-08-20 18:27:03 +000037#include "clang/Sema/ParsedTemplate.h"
John McCall7cd088e2010-08-24 07:21:54 +000038#include "clang/Sema/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000039using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000040using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000041
David Chisnall0f436562009-08-17 16:35:33 +000042
Douglas Gregor48f3bb92009-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 Jahanian8e5fc9b2010-12-21 00:44:01 +000052/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattner52338262009-10-25 22:31:57 +000053/// decls.
54///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000055/// \returns true if there was an error (this declaration cannot be
56/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000057///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000058bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Peter Collingbourne743b82b2011-01-02 19:53:12 +000059 bool UnknownObjCClass) {
Douglas Gregor9b623632010-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 Gregor0a0d2b12011-03-23 00:50:03 +000071 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-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 Smith34b41d92011-02-20 03:19:35 +000078 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-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 Smith34b41d92011-02-20 03:19:35 +000083 }
84
Douglas Gregor48f3bb92009-02-18 21:56:37 +000085 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000086 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-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 Gregor25d944a2009-02-24 04:26:15 +000092 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000093
Douglas Gregor0a0d2b12011-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 Carlsson2127ecc2010-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 Gregor48f3bb92009-02-18 21:56:37 +0000124 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000125}
126
Douglas Gregor0a0d2b12011-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 Jahanian5b530052009-05-13 18:09:35 +0000144/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +0000145/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-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 Stump1eb44332009-09-09 15:08:12 +0000149 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000150 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000151 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000152 return;
Douglas Gregor92e986e2010-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 Jahanian88f1ba02009-05-13 23:20:50 +0000156 int sentinelPos = attr->getSentinel();
157 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +0000158
Mike Stump390b4cc2009-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 Jahanian88f1ba02009-05-13 23:20:50 +0000161 unsigned int i = 0;
Fariborz Jahanian236673e2009-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 Stumpac5fc7c2009-08-04 21:02:39 +0000175 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-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 Stumpac5fc7c2009-08-04 21:02:39 +0000185 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000186 // block or function pointer call.
187 QualType Ty = V->getType();
188 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000189 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000190 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
191 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-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 Stumpac5fc7c2009-08-04 21:02:39 +0000205 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000206 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000207 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000208 return;
209
210 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000211 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000212 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-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 Jahanian236673e2009-05-14 18:00:00 +0000222 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000223 return;
224 }
225 while (i < NumArgs-1) {
226 ++i;
227 ++sentinel;
228 }
229 Expr *sentinelExpr = Args[sentinel];
John McCall8eb662e2010-05-06 23:53:00 +0000230 if (!sentinelExpr) return;
231 if (sentinelExpr->isTypeDependent()) return;
232 if (sentinelExpr->isValueDependent()) return;
Anders Carlsson343e6ff2010-11-05 15:21:33 +0000233
234 // nullptr_t is always treated as null.
235 if (sentinelExpr->getType()->isNullPtrType()) return;
236
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000237 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-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 Jahanian5b530052009-05-13 18:09:35 +0000247}
248
Douglas Gregor4b2d3f72009-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 Lattnere7a2e912008-07-25 21:10:04 +0000254//===----------------------------------------------------------------------===//
255// Standard Promotions and Conversions
256//===----------------------------------------------------------------------===//
257
Chris Lattnere7a2e912008-07-25 21:10:04 +0000258/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000259ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000260 QualType Ty = E->getType();
261 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
262
Chris Lattnere7a2e912008-07-25 21:10:04 +0000263 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000264 E = ImpCastExprToType(E, Context.getPointerType(Ty),
265 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-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 Kyrtzidisc39a3d72008-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 McCall7eb0a9e2010-11-24 05:12:34 +0000278 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000279 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
280 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000281 }
John Wiegley429bb272011-04-08 18:41:53 +0000282 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000283}
284
John Wiegley429bb272011-04-08 18:41:53 +0000285ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall0ae287a2010-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 Wiegley429bb272011-04-08 18:41:53 +0000289 if (!E->isGLValue()) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +0000290
John McCall409fa9a2010-12-06 20:48:59 +0000291 QualType T = E->getType();
292 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000293
John McCall409fa9a2010-12-06 20:48:59 +0000294 // Create a load out of an ObjCProperty l-value, if necessary.
295 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +0000296 ExprResult Res = ConvertPropertyForRValue(E);
297 if (Res.isInvalid())
298 return Owned(E);
299 E = Res.take();
John McCall409fa9a2010-12-06 20:48:59 +0000300 if (!E->isGLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000301 return Owned(E);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000302 }
John McCall409fa9a2010-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 Wiegley429bb272011-04-08 18:41:53 +0000310 return Owned(E);
John McCall409fa9a2010-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 Wiegley429bb272011-04-08 18:41:53 +0000318 return Owned(E);
John McCall409fa9a2010-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 Kremenek3aea4da2011-03-01 18:41:00 +0000332 CheckArrayAccess(E);
Ted Kremeneka0125d82011-02-16 01:57:07 +0000333
John Wiegley429bb272011-04-08 18:41:53 +0000334 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
335 E, 0, VK_RValue));
John McCall409fa9a2010-12-06 20:48:59 +0000336}
337
John Wiegley429bb272011-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 Gregora873dfc2010-02-03 00:27:59 +0000346}
347
348
Chris Lattnere7a2e912008-07-25 21:10:04 +0000349/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000350/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000351/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-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 Wiegley429bb272011-04-08 18:41:53 +0000354ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000355 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000356 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
357 if (Res.isInvalid())
358 return Owned(E);
359 E = Res.take();
John McCall0ae287a2010-12-01 04:43:34 +0000360
361 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000362 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCall0ae287a2010-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 Wiegley429bb272011-04-08 18:41:53 +0000383 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
384 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000385 }
386 if (Ty->isPromotableIntegerType()) {
387 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000388 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
389 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000390 }
Eli Friedman04e83572009-08-20 04:21:42 +0000391 }
John Wiegley429bb272011-04-08 18:41:53 +0000392 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000393}
394
Chris Lattner05faf172008-07-25 22:25:12 +0000395/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000396/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000397/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000398ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
399 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000400 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000401
John Wiegley429bb272011-04-08 18:41:53 +0000402 ExprResult Res = UsualUnaryConversions(E);
403 if (Res.isInvalid())
404 return Owned(E);
405 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000406
Chris Lattner05faf172008-07-25 22:25:12 +0000407 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000408 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000409 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
410
411 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000412}
413
Chris Lattner312531a2009-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 Wiegley429bb272011-04-08 18:41:53 +0000416/// interfaces passed by value.
417ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
Chris Lattner40378332010-05-16 04:01:30 +0000418 FunctionDecl *FDecl) {
John Wiegley429bb272011-04-08 18:41:53 +0000419 ExprResult ExprRes = DefaultArgumentPromotion(E);
420 if (ExprRes.isInvalid())
421 return ExprError();
422 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Chris Lattner40378332010-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 Wiegley429bb272011-04-08 18:41:53 +0000428 return Owned(E);
Chris Lattner40378332010-05-16 04:01:30 +0000429
John Wiegley429bb272011-04-08 18:41:53 +0000430 if (E->getType()->isObjCObjectType() &&
431 DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000432 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
John Wiegley429bb272011-04-08 18:41:53 +0000433 << E->getType() << CT))
434 return ExprError();
Douglas Gregor75b699a2009-12-12 07:25:49 +0000435
John Wiegley429bb272011-04-08 18:41:53 +0000436 if (!E->getType()->isPODType() &&
437 DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000438 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
John Wiegley429bb272011-04-08 18:41:53 +0000439 << E->getType() << CT))
440 return ExprError();
Chris Lattner312531a2009-04-12 08:11:20 +0000441
John Wiegley429bb272011-04-08 18:41:53 +0000442 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000443}
444
Chris Lattnere7a2e912008-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 Stump1eb44332009-09-09 15:08:12 +0000447/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-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 Wiegley429bb272011-04-08 18:41:53 +0000451QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
Chris Lattnere7a2e912008-07-25 21:10:04 +0000452 bool isCompAssign) {
John Wiegley429bb272011-04-08 18:41:53 +0000453 if (!isCompAssign) {
454 lhsExpr = UsualUnaryConversions(lhsExpr.take());
455 if (lhsExpr.isInvalid())
456 return QualType();
457 }
Eli Friedmanab3a8522009-03-28 01:22:36 +0000458
John Wiegley429bb272011-04-08 18:41:53 +0000459 rhsExpr = UsualUnaryConversions(rhsExpr.take());
460 if (rhsExpr.isInvalid())
461 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000462
Mike Stump1eb44332009-09-09 15:08:12 +0000463 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000464 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000465 QualType lhs =
John Wiegley429bb272011-04-08 18:41:53 +0000466 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000467 QualType rhs =
John Wiegley429bb272011-04-08 18:41:53 +0000468 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-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 McCallcf33b242010-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 Wiegley429bb272011-04-08 18:41:53 +0000483 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +0000484 if (!LHSBitfieldPromoteTy.isNull())
485 lhs = LHSBitfieldPromoteTy;
John McCallcf33b242010-11-13 08:17:45 +0000486 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000487 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000488
John McCallcf33b242010-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 McCall2bb5d002010-11-13 09:02:35 +0000501 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
502 if (rhs->isIntegerType()) {
503 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000504 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
505 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000506 } else {
507 assert(rhs->isComplexIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +0000508 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000509 }
John McCallcf33b242010-11-13 08:17:45 +0000510 return lhs;
511 }
512
John McCall2bb5d002010-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 Wiegley429bb272011-04-08 18:41:53 +0000518 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
519 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000520 } else {
521 assert(lhs->isComplexIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +0000522 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000523 }
524 }
John McCallcf33b242010-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 Wiegley429bb272011-04-08 18:41:53 +0000544 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000545 return lhs;
546
547 } else if (order < 0) {
548 // _Complex float -> _Complex double
549 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000550 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
John McCallcf33b242010-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 McCall2bb5d002010-11-13 09:02:35 +0000561 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000562 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
563 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCallcf33b242010-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 Wiegley429bb272011-04-08 18:41:53 +0000571 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000572
573 // _Complex float -> _Complex double
574 if (!isCompAssign && order < 0)
John Wiegley429bb272011-04-08 18:41:53 +0000575 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
John McCallcf33b242010-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 McCall2bb5d002010-11-13 09:02:35 +0000586 if (!isCompAssign) {
Argyrios Kyrtzidise1889332011-01-18 18:49:33 +0000587 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000588 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
589 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000590 }
John McCallcf33b242010-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 Wiegley429bb272011-04-08 18:41:53 +0000599 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000600
601 // _Complex float -> _Complex double
602 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +0000603 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
John McCallcf33b242010-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 Wiegley429bb272011-04-08 18:41:53 +0000617 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCallcf33b242010-11-13 08:17:45 +0000618 return lhs;
619 }
620
621 assert(order < 0 && "illegal float comparison");
622 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000623 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCallcf33b242010-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 Wiegley429bb272011-04-08 18:41:53 +0000631 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCallcf33b242010-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 Wiegley429bb272011-04-08 18:41:53 +0000640 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000641
642 // float -> _Complex float
643 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000644 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-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 Wiegley429bb272011-04-08 18:41:53 +0000653 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCallcf33b242010-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 Wiegley429bb272011-04-08 18:41:53 +0000663 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000664
665 // float -> _Complex float
John Wiegley429bb272011-04-08 18:41:53 +0000666 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-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 Wiegley429bb272011-04-08 18:41:53 +0000682 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000683 return lhs;
684 }
685
686 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000687 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000688 return rhs;
689 } else if (lhsComplexInt) {
690 // int -> _Complex int
John Wiegley429bb272011-04-08 18:41:53 +0000691 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000692 return lhs;
693 } else if (rhsComplexInt) {
694 // int -> _Complex int
695 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000696 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
John McCallcf33b242010-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 Wiegley429bb272011-04-08 18:41:53 +0000708 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000709 return lhs;
710 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000711 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-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 Wiegley429bb272011-04-08 18:41:53 +0000717 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000718 return lhs;
719 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000720 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-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 Wiegley429bb272011-04-08 18:41:53 +0000727 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000728 return lhs;
729 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000730 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-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 Wiegley429bb272011-04-08 18:41:53 +0000739 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000740 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000741 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000742 return result;
743 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000744}
745
Chris Lattnere7a2e912008-07-25 21:10:04 +0000746//===----------------------------------------------------------------------===//
747// Semantic Analysis for various Expression Types
748//===----------------------------------------------------------------------===//
749
750
Peter Collingbournef111d932011-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 Kramer5bf47f72011-04-15 11:21:57 +0000775 delete [] Types;
Peter Collingbournef111d932011-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 Narofff69936d2007-09-16 03:34:24 +0000908/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +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 Redlcd965b92009-01-18 18:53:16 +0000913///
John McCall60d7b3a2010-08-24 06:29:42 +0000914ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +0000915Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000916 assert(NumStringToks && "Must have at least one string!");
917
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000918 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000919 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000920 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000921
922 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
923 for (unsigned i = 0; i != NumStringToks; ++i)
924 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000925
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000926 QualType StrTy = Context.CharTy;
Anders Carlsson96b4adc2011-04-06 18:42:48 +0000927 if (Literal.AnyWide)
928 StrTy = Context.getWCharType();
929 else if (Literal.Pascal)
930 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000931
932 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +0000933 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +0000934 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000935
Chris Lattnera7ad98f2008-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 Lattnerdbb1ecc2009-02-26 23:01:51 +0000940 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000941 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Reid Spencer5f016e22007-07-11 17:01:13 +0000943 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +0000944 return Owned(StringLiteral::Create(Context, Literal.GetString(),
945 Literal.GetStringLength(),
Anders Carlsson3e2193c2011-04-14 00:40:03 +0000946 Literal.AnyWide, Literal.Pascal, StrTy,
Sean Hunt6cf75022010-08-30 17:47:05 +0000947 &StringTokLocs[0],
948 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000949}
950
John McCall469a1eb2011-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 McCall6b5a61b2011-02-07 10:33:21 +0000958 /// A by-ref capture is required.
959 CR_CaptureByRef,
960
John McCall469a1eb2011-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 Lattner639e2d32008-10-20 05:16:36 +0000966///
John McCall469a1eb2011-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 McCall6b5a61b2011-02-07 10:33:21 +0000970diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-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 Stump1eb44332009-09-09 15:08:12 +0000976
John McCall469a1eb2011-02-02 13:00:07 +0000977 case Sema::PotentiallyEvaluated:
978 case Sema::PotentiallyEvaluatedIfUsed:
979 break;
Chris Lattner639e2d32008-10-20 05:16:36 +0000980
John McCall469a1eb2011-02-02 13:00:07 +0000981 case Sema::PotentiallyPotentiallyEvaluated:
982 // FIXME: delay these!
983 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000984 }
Mike Stump1eb44332009-09-09 15:08:12 +0000985
John McCall469a1eb2011-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 McCall4f38f412011-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 McCall469a1eb2011-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 Stump1eb44332009-09-09 15:08:12 +00001017}
1018
John McCall6b5a61b2011-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 McCall469a1eb2011-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 McCall6b5a61b2011-02-07 10:33:21 +00001043static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001044 ValueDecl *value) {
1045 // Only variables ever require capture.
1046 VarDecl *var = dyn_cast<VarDecl>(value);
John McCall76a40212011-02-09 01:13:10 +00001047 if (!var) return CR_NoCapture;
John McCall469a1eb2011-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 McCall469a1eb2011-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 McCall6b5a61b2011-02-07 10:33:21 +00001064 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-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 McCall6b5a61b2011-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 McCall469a1eb2011-02-02 13:00:07 +00001075
1076 functionScopesIndex--;
1077 DC = cast<BlockDecl>(DC)->getDeclContext();
1078 } while (var->getDeclContext() != DC);
1079
John McCall6b5a61b2011-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 McCall469a1eb2011-02-02 13:00:07 +00001172}
Chris Lattner639e2d32008-10-20 05:16:36 +00001173
John McCall60d7b3a2010-08-24 06:29:42 +00001174ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001175Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001176 SourceLocation Loc,
1177 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001178 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001179 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001180}
1181
John McCall76a40212011-02-09 01:13:10 +00001182/// BuildDeclRefExpr - Build an expression that references a
1183/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001184ExprResult
John McCall76a40212011-02-09 01:13:10 +00001185Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001186 const DeclarationNameInfo &NameInfo,
1187 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001188 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +00001189
John McCall7eb0a9e2010-11-24 05:12:34 +00001190 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00001191 SS? SS->getWithLocInContext(Context)
1192 : NestedNameSpecifierLoc(),
John McCall7eb0a9e2010-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 Gregor1a49af92009-01-06 05:10:23 +00001200}
1201
John McCalldfa1edb2010-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 McCall60d7b3a2010-08-24 06:29:42 +00001208ExprResult
John McCall5808ce42011-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 Gregorf5848322011-02-18 02:44:58 +00001221 CXXScopeSpec EmptySS;
John McCall5808ce42011-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 Gregorf5848322011-02-18 02:44:58 +00001235 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCall5808ce42011-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 Gregorbcbffc42009-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 McCall5808ce42011-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 Gregorbcbffc42009-01-07 00:43:41 +00001255 }
John McCall5808ce42011-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 Gregorbcbffc42009-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 McCall5808ce42011-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 Gregorbcbffc42009-01-07 00:43:41 +00001269 }
1270
John McCall5808ce42011-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 Gregorbcbffc42009-01-07 00:43:41 +00001277 }
1278
1279 // Build the implicit member references to the field of the
1280 // anonymous struct/union.
John McCall5808ce42011-02-03 08:15:49 +00001281 Expr *result = baseObjectExpr;
1282 IndirectFieldDecl::chain_iterator
1283 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCalldfa1edb2010-11-23 20:48:44 +00001284
John McCall5808ce42011-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 McCalldfa1edb2010-11-23 20:48:44 +00001288
John McCall5808ce42011-02-03 08:15:49 +00001289 // FIXME: use the real found-decl info!
1290 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall0953e762009-09-24 19:53:00 +00001291
John McCall5808ce42011-02-03 08:15:49 +00001292 // Make a nameInfo that properly uses the anonymous name.
1293 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall0953e762009-09-24 19:53:00 +00001294
John McCall5808ce42011-02-03 08:15:49 +00001295 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregorf5848322011-02-18 02:44:58 +00001296 EmptySS, field, foundDecl,
John McCall5808ce42011-02-03 08:15:49 +00001297 memberNameInfo).take();
1298 baseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +00001299
John McCall5808ce42011-02-03 08:15:49 +00001300 // FIXME: check qualified member access
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001301 }
1302
John McCall5808ce42011-02-03 08:15:49 +00001303 // In all cases, we should now skip the first declaration in the chain.
1304 ++FI;
1305
Douglas Gregorf5848322011-02-18 02:44:58 +00001306 while (FI != FEnd) {
1307 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCall5808ce42011-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 McCall5808ce42011-02-03 08:15:49 +00001312
1313 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregorf5848322011-02-18 02:44:58 +00001314 (FI == FEnd? SS : EmptySS), field,
1315 foundDecl, memberNameInfo)
John McCall5808ce42011-02-03 08:15:49 +00001316 .take();
1317 }
1318
1319 return Owned(result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001320}
1321
Abramo Bagnara25777432010-08-11 22:01:17 +00001322/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-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 Bagnara25777432010-08-11 22:01:17 +00001334 DeclarationNameInfo &NameInfo,
John McCall129e2df2009-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 McCall2b5289b2010-08-23 07:28:44 +00001346 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001347 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1348 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001349 TemplateArgs = &Buffer;
1350 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001351 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001352 TemplateArgs = 0;
1353 }
1354}
1355
John McCallaa81e162009-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 McCallb1b42562009-12-01 22:28:41 +00001361 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +00001362 return false;
1363
Douglas Gregor952b0172010-02-11 01:04:33 +00001364 RecordDecl *RD = Record->getDefinition();
John McCallb1b42562009-12-01 22:28:41 +00001365 if (!RD) return false;
1366 Record = cast<CXXRecordDecl>(RD);
1367
John McCallaa81e162009-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 McCallaa81e162009-12-01 22:10:20 +00001375 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1376 return false;
1377 }
1378
1379 return true;
1380}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001381
John McCallaa81e162009-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 McCallaa81e162009-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 McCall3b4294e2009-12-16 12:17:52 +00001424 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +00001425
John McCallea1471e2010-05-20 01:18:31 +00001426 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCallaa81e162009-12-01 22:10:20 +00001427 bool isStaticContext =
John McCallea1471e2010-05-20 01:18:31 +00001428 (!isa<CXXMethodDecl>(DC) ||
1429 cast<CXXMethodDecl>(DC)->isStatic());
John McCallaa81e162009-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 Redlf9780002010-11-26 16:28:07 +00001436 bool hasField = false;
John McCallaa81e162009-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 McCall161755a2010-04-06 21:38:20 +00001439 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00001440
John McCall161755a2010-04-06 21:38:20 +00001441 if (D->isCXXInstanceMember()) {
Sebastian Redlf9780002010-11-26 16:28:07 +00001442 if (dyn_cast<FieldDecl>(D))
1443 hasField = true;
1444
John McCallaa81e162009-12-01 22:10:20 +00001445 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCallaa81e162009-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 Redlf9780002010-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 McCallaa81e162009-12-01 22:10:20 +00001477
Argyrios Kyrtzidis0d8dc462011-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 McCallaa81e162009-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 Kyrtzidis0d8dc462011-04-14 00:46:47 +00001495 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
John McCallaa81e162009-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 McCall5808ce42011-02-03 08:15:49 +00001504 NamedDecl *rep,
1505 const DeclarationNameInfo &nameInfo) {
1506 SourceLocation Loc = nameInfo.getLoc();
John McCallaa81e162009-12-01 22:10:20 +00001507 SourceRange Range(Loc);
1508 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1509
John McCall5808ce42011-02-03 08:15:49 +00001510 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCallaa81e162009-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 McCall5808ce42011-02-03 08:15:49 +00001515 << Range << nameInfo.getName();
John McCallaa81e162009-12-01 22:10:20 +00001516 return;
1517 }
1518 }
1519
1520 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCall5808ce42011-02-03 08:15:49 +00001521 << nameInfo.getName() << Range;
John McCallaa81e162009-12-01 22:10:20 +00001522 return;
1523 }
1524
1525 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +00001526}
1527
John McCall578b69b2009-12-16 08:11:27 +00001528/// Diagnose an empty lookup.
1529///
1530/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001531bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1532 CorrectTypoContext CTC) {
John McCall578b69b2009-12-16 08:11:27 +00001533 DeclarationName Name = R.getLookupName();
1534
John McCall578b69b2009-12-16 08:11:27 +00001535 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001536 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001537 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1538 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001539 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001540 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001541 diagnostic_suggest = diag::err_undeclared_use_suggest;
1542 }
John McCall578b69b2009-12-16 08:11:27 +00001543
Douglas Gregorbb092ba2009-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 Lewycky03d98c52010-07-06 19:51:49 +00001548 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001549 DC; DC = DC->getParent()) {
John McCall578b69b2009-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 Lewycky03d98c52010-07-06 19:51:49 +00001565 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001566 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1567 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001568 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001569 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001570 if (DepMethod) {
Nick Lewyckyd9ca4ab2010-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 Gregor7c3179c2011-02-28 18:50:33 +00001579
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001580 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00001581 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001582 CXXDependentScopeMemberExpr *DepExpr =
1583 CXXDependentScopeMemberExpr::Create(
1584 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001585 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001586 R.getLookupNameInfo(), &TList);
1587 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001588 } else {
Nick Lewyckyd9ca4ab2010-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 Friedmana7e68452010-08-22 01:00:03 +00001592 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001593 } else {
John McCall578b69b2009-12-16 08:11:27 +00001594 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001595 }
John McCall578b69b2009-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 Gregore26f0432010-08-09 22:38:14 +00001604
1605 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001606 }
1607 }
1608
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001609 // We didn't find anything, so try to correct for a typo.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001610 DeclarationName Corrected;
Daniel Dunbardc32cdf2010-06-02 15:46:52 +00001611 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregoraaf87162010-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 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001631
Douglas Gregoraaf87162010-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 {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001649 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001650 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001651 if (SS.isEmpty())
Douglas Gregoraaf87162010-04-14 20:04:41 +00001652 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001653 else
Douglas Gregord203a162010-01-01 00:15:04 +00001654 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001655 << Name << computeDeclContext(SS, false) << Corrected
1656 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001657 return true;
1658 }
Douglas Gregord203a162010-01-01 00:15:04 +00001659 R.clear();
Douglas Gregorbb092ba2009-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 McCall578b69b2009-12-16 08:11:27 +00001671 // Give up, we can't recover.
1672 Diag(R.getNameLoc(), diagnostic) << Name;
1673 return true;
1674}
1675
Douglas Gregorca45da02010-11-02 20:36:02 +00001676ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1677 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian69d56242010-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 Gregorca45da02010-11-02 20:36:02 +00001684 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001685 if (!property)
1686 return 0;
1687 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregorca45da02010-11-02 20:36:02 +00001688 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1689 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001690 return 0;
1691 return property;
1692}
1693
Douglas Gregorca45da02010-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 Jahanianad51e742010-07-17 00:59:30 +00001711static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001712 LookupResult &Lookup,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001713 IdentifierInfo *II,
1714 SourceLocation NameLoc) {
1715 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian73f666f2010-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 Jahaniand0fbadd2011-01-26 00:57:01 +00001723 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1724 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001725 if (!LookForIvars)
1726 return 0;
1727
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001728 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1729 if (!IDecl)
1730 return 0;
1731 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001732 if (!ClassImpDecl)
1733 return 0;
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001734 bool DynamicImplSeen = false;
1735 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1736 if (!property)
1737 return 0;
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001738 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001739 DynamicImplSeen =
1740 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian43e1b462010-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 Jahanianad51e742010-07-17 00:59:30 +00001746 if (!DynamicImplSeen) {
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001747 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1748 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001749 NameLoc, NameLoc,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001750 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian75049662010-12-15 23:29:04 +00001751 ObjCIvarDecl::Private,
Fariborz Jahanianad51e742010-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 McCall60d7b3a2010-08-24 06:29:42 +00001761ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001762 CXXScopeSpec &SS,
1763 UnqualifiedId &Id,
1764 bool HasTrailingLParen,
1765 bool isAddressOfOperand) {
John McCallf7a1a742009-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 Gregor4c921ae2009-01-30 01:04:22 +00001770 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001771
John McCall129e2df2009-11-30 22:42:35 +00001772 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001773
1774 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001775 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001776 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnara25777432010-08-11 22:01:17 +00001777 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001778
Abramo Bagnara25777432010-08-11 22:01:17 +00001779 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001780 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001781 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001782
John McCallf7a1a742009-11-24 19:00:30 +00001783 // C++ [temp.dep.expr]p3:
1784 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-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 McCallf7a1a742009-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 Friedman647c8b32010-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 Lattner337e5502011-02-18 01:27:55 +00001799 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001800 if (RequireCompleteDeclContext(SS, DC))
1801 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001802 } else {
1803 DependentID = true;
1804 }
1805 }
1806
Chris Lattner337e5502011-02-18 01:27:55 +00001807 if (DependentID)
Abramo Bagnara25777432010-08-11 22:01:17 +00001808 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001809 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001810
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001811 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001812 // Perform the required lookup.
Abramo Bagnara25777432010-08-11 22:01:17 +00001813 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001814 if (TemplateArgs) {
Douglas Gregord2235f62010-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 Gregor1fd6d442010-05-21 23:18:07 +00001820 bool MemberOfUnknownSpecialization;
1821 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1822 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001823
1824 if (MemberOfUnknownSpecialization ||
1825 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1826 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1827 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001828 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001829 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001830 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Douglas Gregor2f9f89c2011-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 McCallf7a1a742009-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 Jahanian48c2d562010-01-12 23:58:59 +00001840 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001841 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001842 if (E.isInvalid())
1843 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Chris Lattner337e5502011-02-18 01:27:55 +00001845 if (Expr *Ex = E.takeAs<Expr>())
1846 return Owned(Ex);
1847
1848 // Synthesize ivars lazily.
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001849 if (getLangOptions().ObjCDefaultSynthProperties &&
1850 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahaniande267602010-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 Jahanianad51e742010-07-17 00:59:30 +00001857 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1858 isAddressOfOperand);
Fariborz Jahaniande267602010-11-17 19:41:23 +00001859 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001860 }
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001861 // for further use, this must be set to false if in class method.
1862 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001863 }
Chris Lattner8a934232008-03-31 00:36:02 +00001864 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001865
John McCallf7a1a742009-11-24 19:00:30 +00001866 if (R.isAmbiguous())
1867 return ExprError();
1868
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001869 // Determine whether this name might be a candidate for
1870 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001871 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001872
John McCallf7a1a742009-11-24 19:00:30 +00001873 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001874 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-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 Gregor91f7ac72010-05-18 16:14:23 +00001884 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001885 return ExprError();
1886
1887 assert(!R.empty() &&
1888 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001889
1890 // If we found an Objective-C instance variable, let
1891 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001892 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001893 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1894 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001895 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001896 assert(E.isInvalid() || E.get());
1897 return move(E);
1898 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001899 }
1900 }
Mike Stump1eb44332009-09-09 15:08:12 +00001901
John McCallf7a1a742009-11-24 19:00:30 +00001902 // This is guaranteed from this point on.
1903 assert(!R.empty() || ADL);
1904
John McCallaa81e162009-12-01 22:10:20 +00001905 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-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 McCall9c72c602010-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 McCall3b4294e2009-12-16 12:17:52 +00001929 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-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 Gregore2248be2010-08-30 16:00:47 +00001937 else if (R.isUnresolvableResult())
1938 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001939 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001940 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1941 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001942
1943 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001944 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001945 }
1946
John McCallf7a1a742009-11-24 19:00:30 +00001947 if (TemplateArgs)
1948 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001949
John McCallf7a1a742009-11-24 19:00:30 +00001950 return BuildDeclarationNameExpr(SS, R, ADL);
1951}
1952
John McCall3b4294e2009-12-16 12:17:52 +00001953/// Builds an expression which might be an implicit member expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001954ExprResult
John McCall3b4294e2009-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 McCall3b4294e2009-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 McCall5808ce42011-02-03 08:15:49 +00001976 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1977 R.getLookupNameInfo());
John McCall3b4294e2009-12-16 12:17:52 +00001978 return ExprError();
1979 }
1980
1981 llvm_unreachable("unexpected instance member access kind");
1982 return ExprError();
1983}
1984
John McCall129e2df2009-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 McCall60d7b3a2010-08-24 06:29:42 +00001989ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001990Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001991 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001992 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001993 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001994 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001995
John McCall77bb1aa2010-05-01 00:40:08 +00001996 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001997 return ExprError();
1998
Abramo Bagnara25777432010-08-11 22:01:17 +00001999 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00002000 LookupQualifiedName(R, DC);
2001
2002 if (R.isAmbiguous())
2003 return ExprError();
2004
2005 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002006 Diag(NameInfo.getLoc(), diag::err_no_member)
2007 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-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 McCall60d7b3a2010-08-24 06:29:42 +00002022ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002023Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00002024 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00002025 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00002026 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002027
John McCallf7a1a742009-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 Lattneraec43db2010-04-12 05:10:17 +00002037 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-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 Jahanian412e7982010-02-09 19:31:38 +00002047 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00002048 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00002049 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-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 Rajaratnam19357542010-03-13 10:17:05 +00002075 SelfName.setIdentifier(&II, SourceLocation());
John McCallf7a1a742009-11-24 19:00:30 +00002076 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00002077 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00002078 SelfName, false, false);
2079 if (SelfExpr.isInvalid())
2080 return ExprError();
2081
John Wiegley429bb272011-04-08 18:41:53 +00002082 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2083 if (SelfExpr.isInvalid())
2084 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00002085
John McCallf7a1a742009-11-24 19:00:30 +00002086 MarkDeclarationReferenced(Loc, IV);
Fariborz Jahanianb8f17ab2011-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)) {
2092 Diag(Loc, diag::error_implicit_ivar_access)
2093 << IV->getDeclName();
2094 Diag(ND->getLocation(), diag::note_declared_at);
2095 return ExprError();
2096 }
2097 }
John McCallf7a1a742009-11-24 19:00:30 +00002098 return Owned(new (Context)
2099 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00002100 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00002101 }
Chris Lattneraec43db2010-04-12 05:10:17 +00002102 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00002103 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00002104 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00002105 ObjCInterfaceDecl *ClassDeclared;
2106 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2107 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2108 IFace == ClassDeclared)
2109 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2110 }
2111 }
2112
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002113 if (Lookup.empty() && II && AllowBuiltinCreation) {
2114 // FIXME. Consolidate this with similar code in LookupName.
2115 if (unsigned BuiltinID = II->getBuiltinID()) {
2116 if (!(getLangOptions().CPlusPlus &&
2117 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2118 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2119 S, Lookup.isForRedeclaration(),
2120 Lookup.getNameLoc());
2121 if (D) Lookup.addDecl(D);
2122 }
2123 }
2124 }
John McCallf7a1a742009-11-24 19:00:30 +00002125 // Sentinel value saying that we didn't do anything special.
2126 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002127}
John McCallba135432009-11-21 08:51:07 +00002128
John McCall6bb80172010-03-30 21:47:33 +00002129/// \brief Cast a base object to a member's actual type.
2130///
2131/// Logically this happens in three phases:
2132///
2133/// * First we cast from the base type to the naming class.
2134/// The naming class is the class into which we were looking
2135/// when we found the member; it's the qualifier type if a
2136/// qualifier was provided, and otherwise it's the base type.
2137///
2138/// * Next we cast from the naming class to the declaring class.
2139/// If the member we found was brought into a class's scope by
2140/// a using declaration, this is that class; otherwise it's
2141/// the class declaring the member.
2142///
2143/// * Finally we cast from the declaring class to the "true"
2144/// declaring class of the member. This conversion does not
2145/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002146ExprResult
2147Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002148 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002149 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002150 NamedDecl *Member) {
2151 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2152 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002153 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002154
Douglas Gregor5fccd362010-03-03 23:55:11 +00002155 QualType DestRecordType;
2156 QualType DestType;
2157 QualType FromRecordType;
2158 QualType FromType = From->getType();
2159 bool PointerConversions = false;
2160 if (isa<FieldDecl>(Member)) {
2161 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002162
Douglas Gregor5fccd362010-03-03 23:55:11 +00002163 if (FromType->getAs<PointerType>()) {
2164 DestType = Context.getPointerType(DestRecordType);
2165 FromRecordType = FromType->getPointeeType();
2166 PointerConversions = true;
2167 } else {
2168 DestType = DestRecordType;
2169 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002170 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002171 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2172 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002173 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002174
Douglas Gregor5fccd362010-03-03 23:55:11 +00002175 DestType = Method->getThisType(Context);
2176 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002177
Douglas Gregor5fccd362010-03-03 23:55:11 +00002178 if (FromType->getAs<PointerType>()) {
2179 FromRecordType = FromType->getPointeeType();
2180 PointerConversions = true;
2181 } else {
2182 FromRecordType = FromType;
2183 DestType = DestRecordType;
2184 }
2185 } else {
2186 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002187 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002188 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002189
Douglas Gregor5fccd362010-03-03 23:55:11 +00002190 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002191 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002192
Douglas Gregor5fccd362010-03-03 23:55:11 +00002193 // If the unqualified types are the same, no conversion is necessary.
2194 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002195 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002196
John McCall6bb80172010-03-30 21:47:33 +00002197 SourceRange FromRange = From->getSourceRange();
2198 SourceLocation FromLoc = FromRange.getBegin();
2199
John McCall5baba9d2010-08-25 10:28:54 +00002200 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00002201
Douglas Gregor5fccd362010-03-03 23:55:11 +00002202 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002203 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002204 // class name.
2205 //
2206 // If the member was a qualified name and the qualified referred to a
2207 // specific base subobject type, we'll cast to that intermediate type
2208 // first and then to the object in which the member is declared. That allows
2209 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2210 //
2211 // class Base { public: int x; };
2212 // class Derived1 : public Base { };
2213 // class Derived2 : public Base { };
2214 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2215 //
2216 // void VeryDerived::f() {
2217 // x = 17; // error: ambiguous base subobjects
2218 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2219 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002220 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002221 QualType QType = QualType(Qualifier->getAsType(), 0);
2222 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2223 assert(QType->isRecordType() && "lookup done with non-record type");
2224
2225 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2226
2227 // In C++98, the qualifier type doesn't actually have to be a base
2228 // type of the object type, in which case we just ignore it.
2229 // Otherwise build the appropriate casts.
2230 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002231 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002232 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002233 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002234 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002235
Douglas Gregor5fccd362010-03-03 23:55:11 +00002236 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002237 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002238 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2239 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002240
2241 FromType = QType;
2242 FromRecordType = QRecordType;
2243
2244 // If the qualifier type was the same as the destination type,
2245 // we're done.
2246 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002247 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002248 }
2249 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002250
John McCall6bb80172010-03-30 21:47:33 +00002251 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002252
John McCall6bb80172010-03-30 21:47:33 +00002253 // If we actually found the member through a using declaration, cast
2254 // down to the using declaration's type.
2255 //
2256 // Pointer equality is fine here because only one declaration of a
2257 // class ever has member declarations.
2258 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2259 assert(isa<UsingShadowDecl>(FoundDecl));
2260 QualType URecordType = Context.getTypeDeclType(
2261 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2262
2263 // We only need to do this if the naming-class to declaring-class
2264 // conversion is non-trivial.
2265 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2266 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002267 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002268 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002269 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002270 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002271
John McCall6bb80172010-03-30 21:47:33 +00002272 QualType UType = URecordType;
2273 if (PointerConversions)
2274 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002275 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2276 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002277 FromType = UType;
2278 FromRecordType = URecordType;
2279 }
2280
2281 // We don't do access control for the conversion from the
2282 // declaring class to the true declaring class.
2283 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002284 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002285
John McCallf871d0c2010-08-07 06:22:56 +00002286 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002287 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2288 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002289 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002290 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002291
John Wiegley429bb272011-04-08 18:41:53 +00002292 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2293 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002294}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002295
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002296/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00002297static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00002298 const CXXScopeSpec &SS, ValueDecl *Member,
John McCall161755a2010-04-06 21:38:20 +00002299 DeclAccessPair FoundDecl,
Abramo Bagnara25777432010-08-11 22:01:17 +00002300 const DeclarationNameInfo &MemberNameInfo,
2301 QualType Ty,
John McCallf89e55a2010-11-18 06:31:45 +00002302 ExprValueKind VK, ExprObjectKind OK,
John McCallf7a1a742009-11-24 19:00:30 +00002303 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregor40d96a62011-02-28 21:54:11 +00002304 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnara25777432010-08-11 22:01:17 +00002305 Member, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002306 TemplateArgs, Ty, VK, OK);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002307}
2308
John McCalldfa1edb2010-11-23 20:48:44 +00002309static ExprResult
2310BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2311 const CXXScopeSpec &SS, FieldDecl *Field,
2312 DeclAccessPair FoundDecl,
2313 const DeclarationNameInfo &MemberNameInfo) {
2314 // x.a is an l-value if 'a' has a reference type. Otherwise:
2315 // x.a is an l-value/x-value/pr-value if the base is (and note
2316 // that *x is always an l-value), except that if the base isn't
2317 // an ordinary object then we must have an rvalue.
2318 ExprValueKind VK = VK_LValue;
2319 ExprObjectKind OK = OK_Ordinary;
2320 if (!IsArrow) {
2321 if (BaseExpr->getObjectKind() == OK_Ordinary)
2322 VK = BaseExpr->getValueKind();
2323 else
2324 VK = VK_RValue;
2325 }
2326 if (VK != VK_RValue && Field->isBitField())
2327 OK = OK_BitField;
2328
2329 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2330 QualType MemberType = Field->getType();
2331 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2332 MemberType = Ref->getPointeeType();
2333 VK = VK_LValue;
2334 } else {
2335 QualType BaseType = BaseExpr->getType();
2336 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2337
2338 Qualifiers BaseQuals = BaseType.getQualifiers();
2339
2340 // GC attributes are never picked up by members.
2341 BaseQuals.removeObjCGCAttr();
2342
2343 // CVR attributes from the base are picked up by members,
2344 // except that 'mutable' members don't pick up 'const'.
2345 if (Field->isMutable()) BaseQuals.removeConst();
2346
2347 Qualifiers MemberQuals
2348 = S.Context.getCanonicalType(MemberType).getQualifiers();
2349
2350 // TR 18037 does not allow fields to be declared with address spaces.
2351 assert(!MemberQuals.hasAddressSpace());
2352
2353 Qualifiers Combined = BaseQuals + MemberQuals;
2354 if (Combined != MemberQuals)
2355 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2356 }
2357
2358 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
John Wiegley429bb272011-04-08 18:41:53 +00002359 ExprResult Base =
2360 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2361 FoundDecl, Field);
2362 if (Base.isInvalid())
John McCalldfa1edb2010-11-23 20:48:44 +00002363 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00002364 return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
John McCalldfa1edb2010-11-23 20:48:44 +00002365 Field, FoundDecl, MemberNameInfo,
2366 MemberType, VK, OK));
2367}
2368
John McCallaa81e162009-12-01 22:10:20 +00002369/// Builds an implicit member access expression. The current context
2370/// is known to be an instance method, and the given unqualified lookup
2371/// set is known to contain only instance members, at least one of which
2372/// is from an appropriate type.
John McCall60d7b3a2010-08-24 06:29:42 +00002373ExprResult
John McCallaa81e162009-12-01 22:10:20 +00002374Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2375 LookupResult &R,
2376 const TemplateArgumentListInfo *TemplateArgs,
2377 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00002378 assert(!R.empty() && !R.isAmbiguous());
2379
John McCall5808ce42011-02-03 08:15:49 +00002380 SourceLocation loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00002381
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002382 // We may have found a field within an anonymous union or struct
2383 // (C++ [class.union]).
John McCallf7a1a742009-11-24 19:00:30 +00002384 // FIXME: template-ids inside anonymous structs?
Francois Pichet87c2e122010-11-21 06:08:52 +00002385 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCall5808ce42011-02-03 08:15:49 +00002386 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet87c2e122010-11-21 06:08:52 +00002387
John McCall5808ce42011-02-03 08:15:49 +00002388 // If this is known to be an instance access, go ahead and build an
2389 // implicit 'this' expression now.
John McCallaa81e162009-12-01 22:10:20 +00002390 // 'this' expression now.
John McCall5808ce42011-02-03 08:15:49 +00002391 CXXMethodDecl *method = tryCaptureCXXThis();
2392 assert(method && "didn't correctly pre-flight capture of 'this'");
2393
2394 QualType thisType = method->getThisType(Context);
2395 Expr *baseExpr = 0; // null signifies implicit access
John McCallaa81e162009-12-01 22:10:20 +00002396 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00002397 SourceLocation Loc = R.getNameLoc();
2398 if (SS.getRange().isValid())
2399 Loc = SS.getRange().getBegin();
John McCall5808ce42011-02-03 08:15:49 +00002400 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00002401 }
2402
John McCall5808ce42011-02-03 08:15:49 +00002403 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCallaa81e162009-12-01 22:10:20 +00002404 /*OpLoc*/ SourceLocation(),
2405 /*IsArrow*/ true,
John McCallc2233c52010-01-15 08:34:02 +00002406 SS,
2407 /*FirstQualifierInScope*/ 0,
2408 R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00002409}
2410
John McCallf7a1a742009-11-24 19:00:30 +00002411bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002412 const LookupResult &R,
2413 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002414 // Only when used directly as the postfix-expression of a call.
2415 if (!HasTrailingLParen)
2416 return false;
2417
2418 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002419 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002420 return false;
2421
2422 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002423 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002424 return false;
2425
2426 // Turn off ADL when we find certain kinds of declarations during
2427 // normal lookup:
2428 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2429 NamedDecl *D = *I;
2430
2431 // C++0x [basic.lookup.argdep]p3:
2432 // -- a declaration of a class member
2433 // Since using decls preserve this property, we check this on the
2434 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002435 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002436 return false;
2437
2438 // C++0x [basic.lookup.argdep]p3:
2439 // -- a block-scope function declaration that is not a
2440 // using-declaration
2441 // NOTE: we also trigger this for function templates (in fact, we
2442 // don't check the decl type at all, since all other decl types
2443 // turn off ADL anyway).
2444 if (isa<UsingShadowDecl>(D))
2445 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2446 else if (D->getDeclContext()->isFunctionOrMethod())
2447 return false;
2448
2449 // C++0x [basic.lookup.argdep]p3:
2450 // -- a declaration that is neither a function or a function
2451 // template
2452 // And also for builtin functions.
2453 if (isa<FunctionDecl>(D)) {
2454 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2455
2456 // But also builtin functions.
2457 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2458 return false;
2459 } else if (!isa<FunctionTemplateDecl>(D))
2460 return false;
2461 }
2462
2463 return true;
2464}
2465
2466
John McCallba135432009-11-21 08:51:07 +00002467/// Diagnoses obvious problems with the use of the given declaration
2468/// as an expression. This is only actually called for lookups that
2469/// were not overloaded, and it doesn't promise that the declaration
2470/// will in fact be used.
2471static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2472 if (isa<TypedefDecl>(D)) {
2473 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2474 return true;
2475 }
2476
2477 if (isa<ObjCInterfaceDecl>(D)) {
2478 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2479 return true;
2480 }
2481
2482 if (isa<NamespaceDecl>(D)) {
2483 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2484 return true;
2485 }
2486
2487 return false;
2488}
2489
John McCall60d7b3a2010-08-24 06:29:42 +00002490ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002491Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002492 LookupResult &R,
2493 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002494 // If this is a single, fully-resolved result and we don't need ADL,
2495 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002496 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002497 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2498 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002499
2500 // We only need to check the declaration if there's exactly one
2501 // result, because in the overloaded case the results can only be
2502 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002503 if (R.isSingleResult() &&
2504 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002505 return ExprError();
2506
John McCallc373d482010-01-27 01:50:18 +00002507 // Otherwise, just build an unresolved lookup expression. Suppress
2508 // any lookup-related diagnostics; we'll hash these out later, when
2509 // we've picked a target.
2510 R.suppressDiagnostics();
2511
John McCallba135432009-11-21 08:51:07 +00002512 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002513 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002514 SS.getWithLocInContext(Context),
2515 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002516 NeedsADL, R.isOverloadedResult(),
2517 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002518
2519 return Owned(ULE);
2520}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002521
John McCallba135432009-11-21 08:51:07 +00002522/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002523ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002524Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002525 const DeclarationNameInfo &NameInfo,
2526 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002527 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002528 assert(!isa<FunctionTemplateDecl>(D) &&
2529 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002530
Abramo Bagnara25777432010-08-11 22:01:17 +00002531 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002532 if (CheckDeclInExpr(*this, Loc, D))
2533 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002534
Douglas Gregor9af2f522009-12-01 16:58:18 +00002535 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2536 // Specifically diagnose references to class templates that are missing
2537 // a template argument list.
2538 Diag(Loc, diag::err_template_decl_ref)
2539 << Template << SS.getRange();
2540 Diag(Template->getLocation(), diag::note_template_decl_here);
2541 return ExprError();
2542 }
2543
2544 // Make sure that we're referring to a value.
2545 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2546 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002547 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002548 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002549 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002550 return ExprError();
2551 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002552
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002553 // Check whether this declaration can be used. Note that we suppress
2554 // this check when we're going to perform argument-dependent lookup
2555 // on this function name, because this might not be the function
2556 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002557 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002558 return ExprError();
2559
Steve Naroffdd972f22008-09-05 22:11:13 +00002560 // Only create DeclRefExpr's for valid Decl's.
2561 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002562 return ExprError();
2563
John McCall5808ce42011-02-03 08:15:49 +00002564 // Handle members of anonymous structs and unions. If we got here,
2565 // and the reference is to a class member indirect field, then this
2566 // must be the subject of a pointer-to-member expression.
2567 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2568 if (!indirectField->isCXXClassMember())
2569 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2570 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002571
Chris Lattner639e2d32008-10-20 05:16:36 +00002572 // If the identifier reference is inside a block, and it refers to a value
2573 // that is outside the block, create a BlockDeclRefExpr instead of a
2574 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2575 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002576 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002577 // We do not do this for things like enum constants, global variables, etc,
2578 // as they do not get snapshotted.
2579 //
John McCall6b5a61b2011-02-07 10:33:21 +00002580 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002581 case CR_Error:
2582 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002583
John McCall469a1eb2011-02-02 13:00:07 +00002584 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002585 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2586 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2587
2588 case CR_CaptureByRef:
2589 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2590 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002591
2592 case CR_NoCapture: {
2593 // If this reference is not in a block or if the referenced
2594 // variable is within the block, create a normal DeclRefExpr.
2595
2596 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002597 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002598
2599 switch (D->getKind()) {
2600 // Ignore all the non-ValueDecl kinds.
2601#define ABSTRACT_DECL(kind)
2602#define VALUE(type, base)
2603#define DECL(type, base) \
2604 case Decl::type:
2605#include "clang/AST/DeclNodes.inc"
2606 llvm_unreachable("invalid value decl kind");
2607 return ExprError();
2608
2609 // These shouldn't make it here.
2610 case Decl::ObjCAtDefsField:
2611 case Decl::ObjCIvar:
2612 llvm_unreachable("forming non-member reference to ivar?");
2613 return ExprError();
2614
2615 // Enum constants are always r-values and never references.
2616 // Unresolved using declarations are dependent.
2617 case Decl::EnumConstant:
2618 case Decl::UnresolvedUsingValue:
2619 valueKind = VK_RValue;
2620 break;
2621
2622 // Fields and indirect fields that got here must be for
2623 // pointer-to-member expressions; we just call them l-values for
2624 // internal consistency, because this subexpression doesn't really
2625 // exist in the high-level semantics.
2626 case Decl::Field:
2627 case Decl::IndirectField:
2628 assert(getLangOptions().CPlusPlus &&
2629 "building reference to field in C?");
2630
2631 // These can't have reference type in well-formed programs, but
2632 // for internal consistency we do this anyway.
2633 type = type.getNonReferenceType();
2634 valueKind = VK_LValue;
2635 break;
2636
2637 // Non-type template parameters are either l-values or r-values
2638 // depending on the type.
2639 case Decl::NonTypeTemplateParm: {
2640 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2641 type = reftype->getPointeeType();
2642 valueKind = VK_LValue; // even if the parameter is an r-value reference
2643 break;
2644 }
2645
2646 // For non-references, we need to strip qualifiers just in case
2647 // the template parameter was declared as 'const int' or whatever.
2648 valueKind = VK_RValue;
2649 type = type.getUnqualifiedType();
2650 break;
2651 }
2652
2653 case Decl::Var:
2654 // In C, "extern void blah;" is valid and is an r-value.
2655 if (!getLangOptions().CPlusPlus &&
2656 !type.hasQualifiers() &&
2657 type->isVoidType()) {
2658 valueKind = VK_RValue;
2659 break;
2660 }
2661 // fallthrough
2662
2663 case Decl::ImplicitParam:
2664 case Decl::ParmVar:
2665 // These are always l-values.
2666 valueKind = VK_LValue;
2667 type = type.getNonReferenceType();
2668 break;
2669
2670 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002671 const FunctionType *fty = type->castAs<FunctionType>();
2672
2673 // If we're referring to a function with an __unknown_anytype
2674 // result type, make the entire expression __unknown_anytype.
2675 if (fty->getResultType() == Context.UnknownAnyTy) {
2676 type = Context.UnknownAnyTy;
2677 valueKind = VK_RValue;
2678 break;
2679 }
2680
John McCall76a40212011-02-09 01:13:10 +00002681 // Functions are l-values in C++.
2682 if (getLangOptions().CPlusPlus) {
2683 valueKind = VK_LValue;
2684 break;
2685 }
2686
2687 // C99 DR 316 says that, if a function type comes from a
2688 // function definition (without a prototype), that type is only
2689 // used for checking compatibility. Therefore, when referencing
2690 // the function, we pretend that we don't have the full function
2691 // type.
John McCall755d8492011-04-12 00:42:48 +00002692 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2693 isa<FunctionProtoType>(fty))
2694 type = Context.getFunctionNoProtoType(fty->getResultType(),
2695 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002696
2697 // Functions are r-values in C.
2698 valueKind = VK_RValue;
2699 break;
2700 }
2701
2702 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002703 // If we're referring to a method with an __unknown_anytype
2704 // result type, make the entire expression __unknown_anytype.
2705 // This should only be possible with a type written directly.
2706 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2707 if (proto->getResultType() == Context.UnknownAnyTy) {
2708 type = Context.UnknownAnyTy;
2709 valueKind = VK_RValue;
2710 break;
2711 }
2712
John McCall76a40212011-02-09 01:13:10 +00002713 // C++ methods are l-values if static, r-values if non-static.
2714 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2715 valueKind = VK_LValue;
2716 break;
2717 }
2718 // fallthrough
2719
2720 case Decl::CXXConversion:
2721 case Decl::CXXDestructor:
2722 case Decl::CXXConstructor:
2723 valueKind = VK_RValue;
2724 break;
2725 }
2726
2727 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2728 }
2729
John McCall469a1eb2011-02-02 13:00:07 +00002730 }
John McCallf89e55a2010-11-18 06:31:45 +00002731
John McCall6b5a61b2011-02-07 10:33:21 +00002732 llvm_unreachable("unknown capture result");
2733 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002734}
2735
John McCall755d8492011-04-12 00:42:48 +00002736ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002737 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002738
Reid Spencer5f016e22007-07-11 17:01:13 +00002739 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002740 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002741 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2742 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2743 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002744 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002745
Chris Lattnerfa28b302008-01-12 08:14:25 +00002746 // Pre-defined identifiers are of type char[x], where x is the length of the
2747 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002748
Anders Carlsson3a082d82009-09-08 18:24:21 +00002749 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002750 if (!currentDecl && getCurBlock())
2751 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002752 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002753 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002754 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002755 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002756
Anders Carlsson773f3972009-09-11 01:22:35 +00002757 QualType ResTy;
2758 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2759 ResTy = Context.DependentTy;
2760 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002761 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002762
Anders Carlsson773f3972009-09-11 01:22:35 +00002763 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002764 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002765 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2766 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002767 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002768}
2769
John McCall60d7b3a2010-08-24 06:29:42 +00002770ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002771 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002772 bool Invalid = false;
2773 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2774 if (Invalid)
2775 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002776
Benjamin Kramerddeea562010-02-27 13:44:12 +00002777 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2778 PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002779 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002780 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002781
Chris Lattnere8337df2009-12-30 21:19:39 +00002782 QualType Ty;
2783 if (!getLangOptions().CPlusPlus)
2784 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2785 else if (Literal.isWide())
2786 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002787 else if (Literal.isMultiChar())
2788 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002789 else
2790 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002791
Sebastian Redle91b3bc2009-01-20 22:23:13 +00002792 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2793 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00002794 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002795}
2796
John McCall60d7b3a2010-08-24 06:29:42 +00002797ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002798 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002799 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2800 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002801 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00002802 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002803 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002804 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002805 }
Ted Kremenek28396602009-01-13 23:19:12 +00002806
Reid Spencer5f016e22007-07-11 17:01:13 +00002807 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002808 // Add padding so that NumericLiteralParser can overread by one character.
2809 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002810 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002811
Reid Spencer5f016e22007-07-11 17:01:13 +00002812 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002813 bool Invalid = false;
2814 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2815 if (Invalid)
2816 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002817
Mike Stump1eb44332009-09-09 15:08:12 +00002818 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002819 Tok.getLocation(), PP);
2820 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002821 return ExprError();
2822
Chris Lattner5d661452007-08-26 03:42:43 +00002823 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002824
Chris Lattner5d661452007-08-26 03:42:43 +00002825 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002826 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002827 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002828 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002829 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002830 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002831 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002832 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002833
2834 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2835
John McCall94c939d2009-12-24 09:08:04 +00002836 using llvm::APFloat;
2837 APFloat Val(Format);
2838
2839 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002840
2841 // Overflow is always an error, but underflow is only an error if
2842 // we underflowed to zero (APFloat reports denormals as underflow).
2843 if ((result & APFloat::opOverflow) ||
2844 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002845 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002846 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002847 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002848 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002849 APFloat::getLargest(Format).toString(buffer);
2850 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002851 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002852 APFloat::getSmallest(Format).toString(buffer);
2853 }
2854
2855 Diag(Tok.getLocation(), diagnostic)
2856 << Ty
2857 << llvm::StringRef(buffer.data(), buffer.size());
2858 }
2859
2860 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002861 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002862
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002863 if (Ty == Context.DoubleTy) {
2864 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002865 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002866 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2867 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002868 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002869 }
2870 }
Chris Lattner5d661452007-08-26 03:42:43 +00002871 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002872 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002873 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002874 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002875
Neil Boothb9449512007-08-29 22:00:19 +00002876 // long long is a C99 feature.
2877 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002878 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002879 Diag(Tok.getLocation(), diag::ext_longlong);
2880
Reid Spencer5f016e22007-07-11 17:01:13 +00002881 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00002882 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002883
Reid Spencer5f016e22007-07-11 17:01:13 +00002884 if (Literal.GetIntegerValue(ResultVal)) {
2885 // If this value didn't fit into uintmax_t, warn and force to ull.
2886 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002887 Ty = Context.UnsignedLongLongTy;
2888 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002889 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002890 } else {
2891 // If this value fits into a ULL, try to figure out what else it fits into
2892 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002893
Reid Spencer5f016e22007-07-11 17:01:13 +00002894 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2895 // be an unsigned int.
2896 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2897
2898 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002899 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002900 if (!Literal.isLong && !Literal.isLongLong) {
2901 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002902 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002903
Reid Spencer5f016e22007-07-11 17:01:13 +00002904 // Does it fit in a unsigned int?
2905 if (ResultVal.isIntN(IntSize)) {
2906 // Does it fit in a signed int?
2907 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002908 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002909 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002910 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002911 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002912 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002913 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002914
Reid Spencer5f016e22007-07-11 17:01:13 +00002915 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002916 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002917 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002918
Reid Spencer5f016e22007-07-11 17:01:13 +00002919 // Does it fit in a unsigned long?
2920 if (ResultVal.isIntN(LongSize)) {
2921 // Does it fit in a signed long?
2922 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002923 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002924 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002925 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002926 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002927 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002928 }
2929
Reid Spencer5f016e22007-07-11 17:01:13 +00002930 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002931 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002932 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002933
Reid Spencer5f016e22007-07-11 17:01:13 +00002934 // Does it fit in a unsigned long long?
2935 if (ResultVal.isIntN(LongLongSize)) {
2936 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002937 // To be compatible with MSVC, hex integer literals ending with the
2938 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002939 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2940 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002941 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002942 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002943 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002944 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002945 }
2946 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002947
Reid Spencer5f016e22007-07-11 17:01:13 +00002948 // If we still couldn't decide a type, we probably have something that
2949 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002950 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002951 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002952 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002953 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002954 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002955
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002956 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002957 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002958 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002959 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002960 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002961
Chris Lattner5d661452007-08-26 03:42:43 +00002962 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2963 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002964 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002965 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002966
2967 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002968}
2969
John McCall60d7b3a2010-08-24 06:29:42 +00002970ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCall9ae2f072010-08-23 23:25:46 +00002971 SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002972 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002973 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002974}
2975
2976/// The UsualUnaryConversions() function is *not* called by this routine.
2977/// See C99 6.3.2.1p[2-4] for more details.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002978bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2979 SourceLocation OpLoc,
2980 SourceRange ExprRange,
2981 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl28507842009-02-26 14:39:58 +00002982 if (exprType->isDependentType())
2983 return false;
2984
Sebastian Redl5d484e82009-11-23 17:18:46 +00002985 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2986 // the result is the size of the referenced type."
2987 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2988 // result shall be the alignment of the referenced type."
2989 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2990 exprType = Ref->getPointeeType();
2991
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002992 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2993 // scalar or vector data type argument..."
2994 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2995 // type (C99 6.2.5p18) or void.
2996 if (ExprKind == UETT_VecStep) {
2997 if (!(exprType->isArithmeticType() || exprType->isVoidType() ||
2998 exprType->isVectorType())) {
2999 Diag(OpLoc, diag::err_vecstep_non_scalar_vector_type)
3000 << exprType << ExprRange;
3001 return true;
3002 }
3003 }
3004
Reid Spencer5f016e22007-07-11 17:01:13 +00003005 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00003006 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003007 // alignof(function) is allowed as an extension.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003008 if (ExprKind == UETT_SizeOf)
3009 Diag(OpLoc, diag::ext_sizeof_function_type)
3010 << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00003011 return false;
3012 }
Mike Stump1eb44332009-09-09 15:08:12 +00003013
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003014 // Allow sizeof(void)/alignof(void) as an extension. vec_step(void) is not
3015 // an extension, as void is a built-in scalar type (OpenCL 1.1 6.1.1).
Chris Lattner01072922009-01-24 19:46:37 +00003016 if (exprType->isVoidType()) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003017 if (ExprKind != UETT_VecStep)
3018 Diag(OpLoc, diag::ext_sizeof_void_type)
3019 << ExprKind << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00003020 return false;
3021 }
Mike Stump1eb44332009-09-09 15:08:12 +00003022
Chris Lattner1efaa952009-04-24 00:30:45 +00003023 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00003024 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003025 << ExprKind << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003026 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003027
Chris Lattner1efaa952009-04-24 00:30:45 +00003028 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCallc12c5bb2010-05-15 11:32:37 +00003029 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003030 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003031 << exprType << (ExprKind == UETT_SizeOf)
3032 << ExprRange;
Chris Lattner5cb10d32009-04-24 22:30:50 +00003033 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00003034 }
Mike Stump1eb44332009-09-09 15:08:12 +00003035
Chris Lattner1efaa952009-04-24 00:30:45 +00003036 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003037}
3038
John McCall2a984ca2010-10-12 00:20:44 +00003039static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
3040 SourceRange ExprRange) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003041 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003042
Mike Stump1eb44332009-09-09 15:08:12 +00003043 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00003044 if (isa<DeclRefExpr>(E))
3045 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00003046
3047 // Cannot know anything else if the expression is dependent.
3048 if (E->isTypeDependent())
3049 return false;
3050
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003051 if (E->getBitField()) {
John McCall2a984ca2010-10-12 00:20:44 +00003052 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003053 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003054 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003055
3056 // Alignment of a field access is always okay, so long as it isn't a
3057 // bit-field.
3058 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00003059 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003060 return false;
3061
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003062 return S.CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
3063 UETT_AlignOf);
3064}
3065
3066bool Sema::CheckVecStepExpr(Expr *E, SourceLocation OpLoc,
3067 SourceRange ExprRange) {
3068 E = E->IgnoreParens();
3069
3070 // Cannot know anything else if the expression is dependent.
3071 if (E->isTypeDependent())
3072 return false;
3073
3074 return CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
3075 UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003076}
3077
Douglas Gregorba498172009-03-13 21:01:28 +00003078/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003079ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003080Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3081 SourceLocation OpLoc,
3082 UnaryExprOrTypeTrait ExprKind,
3083 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003084 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003085 return ExprError();
3086
John McCalla93c9342009-12-07 02:54:59 +00003087 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003088
Douglas Gregorba498172009-03-13 21:01:28 +00003089 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003090 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003091 return ExprError();
3092
3093 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003094 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3095 Context.getSizeType(),
3096 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003097}
3098
3099/// \brief Build a sizeof or alignof expression given an expression
3100/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003101ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003102Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3103 UnaryExprOrTypeTrait ExprKind,
3104 SourceRange R) {
Douglas Gregorba498172009-03-13 21:01:28 +00003105 // Verify that the operand is valid.
3106 bool isInvalid = false;
3107 if (E->isTypeDependent()) {
3108 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003109 } else if (ExprKind == UETT_AlignOf) {
John McCall2a984ca2010-10-12 00:20:44 +00003110 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003111 } else if (ExprKind == UETT_VecStep) {
3112 isInvalid = CheckVecStepExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003113 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00003114 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
3115 isInvalid = true;
John McCall2cd11fe2010-10-12 02:09:17 +00003116 } else if (E->getType()->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00003117 ExprResult PE = CheckPlaceholderExpr(E);
John McCall2cd11fe2010-10-12 02:09:17 +00003118 if (PE.isInvalid()) return ExprError();
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003119 return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind, R);
Douglas Gregorba498172009-03-13 21:01:28 +00003120 } else {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003121 isInvalid = CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, R,
3122 UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003123 }
3124
3125 if (isInvalid)
3126 return ExprError();
3127
3128 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003129 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, E,
3130 Context.getSizeType(),
3131 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003132}
3133
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003134/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3135/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003136/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003137ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003138Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3139 UnaryExprOrTypeTrait ExprKind, bool isType,
3140 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003141 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003142 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003143
Sebastian Redl05189992008-11-11 17:56:53 +00003144 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00003145 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003146 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003147 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003148 }
Sebastian Redl05189992008-11-11 17:56:53 +00003149
Douglas Gregorba498172009-03-13 21:01:28 +00003150 Expr *ArgEx = (Expr *)TyOrEx;
John McCall60d7b3a2010-08-24 06:29:42 +00003151 ExprResult Result
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003152 = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind,
3153 ArgEx->getSourceRange());
Douglas Gregorba498172009-03-13 21:01:28 +00003154
Douglas Gregorba498172009-03-13 21:01:28 +00003155 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003156}
3157
John Wiegley429bb272011-04-08 18:41:53 +00003158static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall09431682010-11-18 19:01:18 +00003159 bool isReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003160 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003161 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003162
John McCallf6a16482010-12-04 03:47:34 +00003163 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003164 if (V.get()->getObjectKind() != OK_Ordinary) {
3165 V = S.DefaultLvalueConversion(V.take());
3166 if (V.isInvalid())
3167 return QualType();
3168 }
John McCallf6a16482010-12-04 03:47:34 +00003169
Chris Lattnercc26ed72007-08-26 05:39:26 +00003170 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003171 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003172 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003173
Chris Lattnercc26ed72007-08-26 05:39:26 +00003174 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003175 if (V.get()->getType()->isArithmeticType())
3176 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003177
John McCall2cd11fe2010-10-12 02:09:17 +00003178 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003179 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003180 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003181 if (PR.get() != V.get()) {
3182 V = move(PR);
John McCall09431682010-11-18 19:01:18 +00003183 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003184 }
3185
Chris Lattnercc26ed72007-08-26 05:39:26 +00003186 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003187 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattnerba27e2a2009-02-17 08:12:06 +00003188 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003189 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003190}
3191
3192
Reid Spencer5f016e22007-07-11 17:01:13 +00003193
John McCall60d7b3a2010-08-24 06:29:42 +00003194ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003195Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003196 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003197 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003198 switch (Kind) {
3199 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003200 case tok::plusplus: Opc = UO_PostInc; break;
3201 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003202 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003203
John McCall9ae2f072010-08-23 23:25:46 +00003204 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003205}
3206
John McCall09431682010-11-18 19:01:18 +00003207/// Expressions of certain arbitrary types are forbidden by C from
3208/// having l-value type. These are:
3209/// - 'void', but not qualified void
3210/// - function types
3211///
3212/// The exact rule here is C99 6.3.2.1:
3213/// An lvalue is an expression with an object type or an incomplete
3214/// type other than void.
3215static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
3216 return ((T->isVoidType() && !T.hasQualifiers()) ||
3217 T->isFunctionType());
3218}
3219
John McCall60d7b3a2010-08-24 06:29:42 +00003220ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003221Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3222 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003223 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003224 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003225 if (Result.isInvalid()) return ExprError();
3226 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003227
John McCall9ae2f072010-08-23 23:25:46 +00003228 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003229
Douglas Gregor337c6b92008-11-19 17:17:41 +00003230 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003231 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003232 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003233 Context.DependentTy,
3234 VK_LValue, OK_Ordinary,
3235 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003236 }
3237
Mike Stump1eb44332009-09-09 15:08:12 +00003238 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003239 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003240 LHSExp->getType()->isEnumeralType() ||
3241 RHSExp->getType()->isRecordType() ||
3242 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00003243 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003244 }
3245
John McCall9ae2f072010-08-23 23:25:46 +00003246 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003247}
3248
3249
John McCall60d7b3a2010-08-24 06:29:42 +00003250ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003251Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3252 Expr *Idx, SourceLocation RLoc) {
3253 Expr *LHSExp = Base;
3254 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003255
Chris Lattner12d9ff62007-07-16 00:14:47 +00003256 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003257 if (!LHSExp->getType()->getAs<VectorType>()) {
3258 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3259 if (Result.isInvalid())
3260 return ExprError();
3261 LHSExp = Result.take();
3262 }
3263 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3264 if (Result.isInvalid())
3265 return ExprError();
3266 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003267
Chris Lattner12d9ff62007-07-16 00:14:47 +00003268 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003269 ExprValueKind VK = VK_LValue;
3270 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003271
Reid Spencer5f016e22007-07-11 17:01:13 +00003272 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003273 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003274 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003275 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003276 Expr *BaseExpr, *IndexExpr;
3277 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003278 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3279 BaseExpr = LHSExp;
3280 IndexExpr = RHSExp;
3281 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003282 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003283 BaseExpr = LHSExp;
3284 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003285 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003286 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00003287 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00003288 BaseExpr = RHSExp;
3289 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003290 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003291 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003292 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003293 BaseExpr = LHSExp;
3294 IndexExpr = RHSExp;
3295 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003296 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003297 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003298 // Handle the uncommon case of "123[Ptr]".
3299 BaseExpr = RHSExp;
3300 IndexExpr = LHSExp;
3301 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003302 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003303 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003304 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003305 VK = LHSExp->getValueKind();
3306 if (VK != VK_RValue)
3307 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003308
Chris Lattner12d9ff62007-07-16 00:14:47 +00003309 // FIXME: need to deal with const...
3310 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003311 } else if (LHSTy->isArrayType()) {
3312 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003313 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003314 // wasn't promoted because of the C90 rule that doesn't
3315 // allow promoting non-lvalue arrays. Warn, then
3316 // force the promotion here.
3317 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3318 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003319 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3320 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003321 LHSTy = LHSExp->getType();
3322
3323 BaseExpr = LHSExp;
3324 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003325 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003326 } else if (RHSTy->isArrayType()) {
3327 // Same as previous, except for 123[f().a] case
3328 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3329 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003330 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3331 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003332 RHSTy = RHSExp->getType();
3333
3334 BaseExpr = RHSExp;
3335 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003336 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003337 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003338 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3339 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003340 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003341 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003342 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003343 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3344 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003345
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003346 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003347 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3348 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003349 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3350
Douglas Gregore7450f52009-03-24 19:52:54 +00003351 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003352 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3353 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003354 // incomplete types are not object types.
3355 if (ResultType->isFunctionType()) {
3356 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3357 << ResultType << BaseExpr->getSourceRange();
3358 return ExprError();
3359 }
Mike Stump1eb44332009-09-09 15:08:12 +00003360
Abramo Bagnara46358452010-09-13 06:50:07 +00003361 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3362 // GNU extension: subscripting on pointer to void
3363 Diag(LLoc, diag::ext_gnu_void_ptr)
3364 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003365
3366 // C forbids expressions of unqualified void type from being l-values.
3367 // See IsCForbiddenLValueType.
3368 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003369 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003370 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003371 PDiag(diag::err_subscript_incomplete_type)
3372 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003373 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003374
Chris Lattner1efaa952009-04-24 00:30:45 +00003375 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003376 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003377 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3378 << ResultType << BaseExpr->getSourceRange();
3379 return ExprError();
3380 }
Mike Stump1eb44332009-09-09 15:08:12 +00003381
John McCall09431682010-11-18 19:01:18 +00003382 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3383 !IsCForbiddenLValueType(Context, ResultType));
3384
Mike Stumpeed9cac2009-02-19 03:04:26 +00003385 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003386 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003387}
3388
John McCall09431682010-11-18 19:01:18 +00003389/// Check an ext-vector component access expression.
3390///
3391/// VK should be set in advance to the value kind of the base
3392/// expression.
3393static QualType
3394CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3395 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003396 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00003397 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3398 // see FIXME there.
3399 //
3400 // FIXME: This logic can be greatly simplified by splitting it along
3401 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00003402 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00003403
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003404 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00003405 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003406
Mike Stumpeed9cac2009-02-19 03:04:26 +00003407 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00003408 // special names that indicate a subset of exactly half the elements are
3409 // to be selected.
3410 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003411
Nate Begeman353417a2009-01-18 01:47:54 +00003412 // This flag determines whether or not CompName has an 's' char prefix,
3413 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00003414 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00003415
John McCall09431682010-11-18 19:01:18 +00003416 bool HasRepeated = false;
3417 bool HasIndex[16] = {};
3418
3419 int Idx;
3420
Nate Begeman8a997642008-05-09 06:41:27 +00003421 // Check that we've found one of the special components, or that the component
3422 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003423 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00003424 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3425 HalvingSwizzle = true;
John McCall09431682010-11-18 19:01:18 +00003426 } else if (!HexSwizzle &&
3427 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3428 do {
3429 if (HasIndex[Idx]) HasRepeated = true;
3430 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003431 compStr++;
John McCall09431682010-11-18 19:01:18 +00003432 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3433 } else {
3434 if (HexSwizzle) compStr++;
3435 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3436 if (HasIndex[Idx]) HasRepeated = true;
3437 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003438 compStr++;
John McCall09431682010-11-18 19:01:18 +00003439 }
Chris Lattner88dca042007-08-02 22:33:49 +00003440 }
Nate Begeman353417a2009-01-18 01:47:54 +00003441
Mike Stumpeed9cac2009-02-19 03:04:26 +00003442 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003443 // We didn't get to the end of the string. This means the component names
3444 // didn't come from the same set *or* we encountered an illegal name.
John McCall09431682010-11-18 19:01:18 +00003445 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00003446 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003447 return QualType();
3448 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003449
Nate Begeman353417a2009-01-18 01:47:54 +00003450 // Ensure no component accessor exceeds the width of the vector type it
3451 // operates on.
3452 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00003453 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003454
3455 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003456 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00003457
3458 while (*compStr) {
3459 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall09431682010-11-18 19:01:18 +00003460 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begeman353417a2009-01-18 01:47:54 +00003461 << baseType << SourceRange(CompLoc);
3462 return QualType();
3463 }
3464 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003465 }
Nate Begeman8a997642008-05-09 06:41:27 +00003466
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003467 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003468 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003469 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00003470 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00003471 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00003472 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00003473 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00003474 if (HexSwizzle)
3475 CompSize--;
3476
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003477 if (CompSize == 1)
3478 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003479
John McCall09431682010-11-18 19:01:18 +00003480 if (HasRepeated) VK = VK_RValue;
3481
3482 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003483 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00003484 // diagostics look bad. We want extended vector types to appear built-in.
John McCall09431682010-11-18 19:01:18 +00003485 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3486 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3487 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00003488 }
3489 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003490}
3491
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003492static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003493 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003494 const Selector &Sel,
3495 ASTContext &Context) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003496 if (Member)
3497 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3498 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003499 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003500 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00003501
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003502 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3503 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003504 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3505 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003506 return D;
3507 }
3508 return 0;
3509}
3510
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003511static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3512 IdentifierInfo *Member,
3513 const Selector &Sel,
3514 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003515 // Check protocols on qualified interfaces.
3516 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003517 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003518 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003519 if (Member)
3520 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3521 GDecl = PD;
3522 break;
3523 }
3524 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003525 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003526 GDecl = OMD;
3527 break;
3528 }
3529 }
3530 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003531 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003532 E = QIdTy->qual_end(); I != E; ++I) {
3533 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003534 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3535 Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003536 if (GDecl)
3537 return GDecl;
3538 }
3539 }
3540 return GDecl;
3541}
Chris Lattner76a642f2009-02-15 22:43:40 +00003542
John McCall60d7b3a2010-08-24 06:29:42 +00003543ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003544Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCallaa81e162009-12-01 22:10:20 +00003545 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00003546 const CXXScopeSpec &SS,
3547 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003548 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003549 const TemplateArgumentListInfo *TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00003550 // Even in dependent contexts, try to diagnose base expressions with
3551 // obviously wrong types, e.g.:
3552 //
3553 // T* t;
3554 // t.f;
3555 //
3556 // In Obj-C++, however, the above expression is valid, since it could be
3557 // accessing the 'f' property if T is an Obj-C interface. The extra check
3558 // allows this, while still reporting an error if T is a struct pointer.
3559 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00003560 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00003561 if (PT && (!getLangOptions().ObjC1 ||
3562 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00003563 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnara25777432010-08-11 22:01:17 +00003564 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00003565 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00003566 return ExprError();
3567 }
3568 }
3569
Abramo Bagnara25777432010-08-11 22:01:17 +00003570 assert(BaseType->isDependentType() ||
3571 NameInfo.getName().isDependentName() ||
Douglas Gregor01e56ae2010-04-12 20:54:26 +00003572 isDependentScopeSpecifier(SS));
John McCall129e2df2009-11-30 22:42:35 +00003573
3574 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3575 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00003576 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003577 IsArrow, OpLoc,
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003578 SS.getWithLocInContext(Context),
John McCall129e2df2009-11-30 22:42:35 +00003579 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003580 NameInfo, TemplateArgs));
John McCall129e2df2009-11-30 22:42:35 +00003581}
3582
3583/// We know that the given qualified member reference points only to
3584/// declarations which do not belong to the static type of the base
3585/// expression. Diagnose the problem.
3586static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3587 Expr *BaseExpr,
3588 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003589 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00003590 NamedDecl *rep,
3591 const DeclarationNameInfo &nameInfo) {
John McCall2f841ba2009-12-02 03:53:29 +00003592 // If this is an implicit member access, use a different set of
3593 // diagnostics.
3594 if (!BaseExpr)
John McCall5808ce42011-02-03 08:15:49 +00003595 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003596
John McCall5808ce42011-02-03 08:15:49 +00003597 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3598 << SS.getRange() << rep << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00003599}
3600
3601// Check whether the declarations we found through a nested-name
3602// specifier in a member expression are actually members of the base
3603// type. The restriction here is:
3604//
3605// C++ [expr.ref]p2:
3606// ... In these cases, the id-expression shall name a
3607// member of the class or of one of its base classes.
3608//
3609// So it's perfectly legitimate for the nested-name specifier to name
3610// an unrelated class, and for us to find an overload set including
3611// decls from classes which are not superclasses, as long as the decl
3612// we actually pick through overload resolution is from a superclass.
3613bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3614 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003615 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003616 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00003617 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3618 if (!BaseRT) {
3619 // We can't check this yet because the base type is still
3620 // dependent.
3621 assert(BaseType->isDependentType());
3622 return false;
3623 }
3624 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00003625
3626 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00003627 // If this is an implicit member reference and we find a
3628 // non-instance member, it's not an error.
John McCall161755a2010-04-06 21:38:20 +00003629 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00003630 return false;
John McCall129e2df2009-11-30 22:42:35 +00003631
John McCallaa81e162009-12-01 22:10:20 +00003632 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman02463762010-07-27 20:51:02 +00003633 DeclContext *DC = (*I)->getDeclContext();
3634 while (DC->isTransparentContext())
3635 DC = DC->getParent();
John McCallaa81e162009-12-01 22:10:20 +00003636
Douglas Gregor9d4bb942010-07-28 22:27:52 +00003637 if (!DC->isRecord())
3638 continue;
3639
John McCallaa81e162009-12-01 22:10:20 +00003640 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman02463762010-07-27 20:51:02 +00003641 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCallaa81e162009-12-01 22:10:20 +00003642
3643 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3644 return false;
3645 }
3646
John McCall5808ce42011-02-03 08:15:49 +00003647 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3648 R.getRepresentativeDecl(),
3649 R.getLookupNameInfo());
John McCallaa81e162009-12-01 22:10:20 +00003650 return true;
3651}
3652
3653static bool
3654LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3655 SourceRange BaseRange, const RecordType *RTy,
John McCallad00b772010-06-16 08:42:20 +00003656 SourceLocation OpLoc, CXXScopeSpec &SS,
3657 bool HasTemplateArgs) {
John McCallaa81e162009-12-01 22:10:20 +00003658 RecordDecl *RDecl = RTy->getDecl();
3659 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003660 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCallaa81e162009-12-01 22:10:20 +00003661 << BaseRange))
3662 return true;
3663
John McCallad00b772010-06-16 08:42:20 +00003664 if (HasTemplateArgs) {
3665 // LookupTemplateName doesn't expect these both to exist simultaneously.
3666 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3667
3668 bool MOUS;
3669 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3670 return false;
3671 }
3672
John McCallaa81e162009-12-01 22:10:20 +00003673 DeclContext *DC = RDecl;
3674 if (SS.isSet()) {
3675 // If the member name was a qualified-id, look into the
3676 // nested-name-specifier.
3677 DC = SemaRef.computeDeclContext(SS, false);
3678
John McCall77bb1aa2010-05-01 00:40:08 +00003679 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCall2f841ba2009-12-02 03:53:29 +00003680 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3681 << SS.getRange() << DC;
3682 return true;
3683 }
3684
John McCallaa81e162009-12-01 22:10:20 +00003685 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003686
John McCallaa81e162009-12-01 22:10:20 +00003687 if (!isa<TypeDecl>(DC)) {
3688 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3689 << DC << SS.getRange();
3690 return true;
John McCall129e2df2009-11-30 22:42:35 +00003691 }
3692 }
3693
John McCallaa81e162009-12-01 22:10:20 +00003694 // The record definition is complete, now look up the member.
3695 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00003696
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003697 if (!R.empty())
3698 return false;
3699
3700 // We didn't find anything with the given name, so try to correct
3701 // for typos.
3702 DeclarationName Name = R.getLookupName();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003703 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00003704 !R.empty() &&
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003705 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3706 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3707 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003708 << FixItHint::CreateReplacement(R.getNameLoc(),
3709 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003710 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3711 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3712 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003713 return false;
3714 } else {
3715 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003716 R.setLookupName(Name);
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003717 }
3718
John McCall129e2df2009-11-30 22:42:35 +00003719 return false;
3720}
3721
John McCall60d7b3a2010-08-24 06:29:42 +00003722ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003723Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003724 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003725 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003726 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003727 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003728 const TemplateArgumentListInfo *TemplateArgs) {
John McCall2f841ba2009-12-02 03:53:29 +00003729 if (BaseType->isDependentType() ||
3730 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall9ae2f072010-08-23 23:25:46 +00003731 return ActOnDependentMemberExpr(Base, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003732 IsArrow, OpLoc,
3733 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003734 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003735
Abramo Bagnara25777432010-08-11 22:01:17 +00003736 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00003737
John McCallaa81e162009-12-01 22:10:20 +00003738 // Implicit member accesses.
3739 if (!Base) {
3740 QualType RecordTy = BaseType;
3741 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3742 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3743 RecordTy->getAs<RecordType>(),
John McCallad00b772010-06-16 08:42:20 +00003744 OpLoc, SS, TemplateArgs != 0))
John McCallaa81e162009-12-01 22:10:20 +00003745 return ExprError();
3746
3747 // Explicit member accesses.
3748 } else {
John Wiegley429bb272011-04-08 18:41:53 +00003749 ExprResult BaseResult = Owned(Base);
John McCall60d7b3a2010-08-24 06:29:42 +00003750 ExprResult Result =
John Wiegley429bb272011-04-08 18:41:53 +00003751 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCalld226f652010-08-21 09:40:31 +00003752 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCallaa81e162009-12-01 22:10:20 +00003753
John Wiegley429bb272011-04-08 18:41:53 +00003754 if (BaseResult.isInvalid())
3755 return ExprError();
3756 Base = BaseResult.take();
3757
John McCallaa81e162009-12-01 22:10:20 +00003758 if (Result.isInvalid()) {
3759 Owned(Base);
3760 return ExprError();
3761 }
3762
3763 if (Result.get())
3764 return move(Result);
Sebastian Redlf3e63372010-05-07 09:25:11 +00003765
3766 // LookupMemberExpr can modify Base, and thus change BaseType
3767 BaseType = Base->getType();
John McCall129e2df2009-11-30 22:42:35 +00003768 }
3769
John McCall9ae2f072010-08-23 23:25:46 +00003770 return BuildMemberReferenceExpr(Base, BaseType,
John McCallc2233c52010-01-15 08:34:02 +00003771 OpLoc, IsArrow, SS, FirstQualifierInScope,
3772 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003773}
3774
John McCall60d7b3a2010-08-24 06:29:42 +00003775ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003776Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCallaa81e162009-12-01 22:10:20 +00003777 SourceLocation OpLoc, bool IsArrow,
3778 const CXXScopeSpec &SS,
John McCallc2233c52010-01-15 08:34:02 +00003779 NamedDecl *FirstQualifierInScope,
John McCall129e2df2009-11-30 22:42:35 +00003780 LookupResult &R,
Douglas Gregor06a9f362010-05-01 20:49:11 +00003781 const TemplateArgumentListInfo *TemplateArgs,
3782 bool SuppressQualifierCheck) {
John McCallaa81e162009-12-01 22:10:20 +00003783 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00003784 if (IsArrow) {
3785 assert(BaseType->isPointerType());
3786 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3787 }
John McCall161755a2010-04-06 21:38:20 +00003788 R.setBaseObjectType(BaseType);
John McCall129e2df2009-11-30 22:42:35 +00003789
Abramo Bagnara25777432010-08-11 22:01:17 +00003790 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3791 DeclarationName MemberName = MemberNameInfo.getName();
3792 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall129e2df2009-11-30 22:42:35 +00003793
3794 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00003795 return ExprError();
3796
John McCall129e2df2009-11-30 22:42:35 +00003797 if (R.empty()) {
3798 // Rederive where we looked up.
3799 DeclContext *DC = (SS.isSet()
3800 ? computeDeclContext(SS, false)
3801 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00003802
John McCall129e2df2009-11-30 22:42:35 +00003803 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00003804 << MemberName << DC
3805 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00003806 return ExprError();
3807 }
3808
John McCallc2233c52010-01-15 08:34:02 +00003809 // Diagnose lookups that find only declarations from a non-base
3810 // type. This is possible for either qualified lookups (which may
3811 // have been qualified with an unrelated type) or implicit member
3812 // expressions (which were found with unqualified lookup and thus
3813 // may have come from an enclosing scope). Note that it's okay for
3814 // lookup to find declarations from a non-base type as long as those
3815 // aren't the ones picked by overload resolution.
3816 if ((SS.isSet() || !BaseExpr ||
3817 (isa<CXXThisExpr>(BaseExpr) &&
3818 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00003819 !SuppressQualifierCheck &&
John McCallc2233c52010-01-15 08:34:02 +00003820 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00003821 return ExprError();
3822
3823 // Construct an unresolved result if we in fact got an unresolved
3824 // result.
3825 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallc373d482010-01-27 01:50:18 +00003826 // Suppress any lookup-related diagnostics; we'll do these when we
3827 // pick a member.
3828 R.suppressDiagnostics();
3829
John McCall129e2df2009-11-30 22:42:35 +00003830 UnresolvedMemberExpr *MemExpr
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003831 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00003832 BaseExpr, BaseExprType,
3833 IsArrow, OpLoc,
Douglas Gregor4c9be892011-02-28 20:01:57 +00003834 SS.getWithLocInContext(Context),
Abramo Bagnara25777432010-08-11 22:01:17 +00003835 MemberNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00003836 TemplateArgs, R.begin(), R.end());
John McCall129e2df2009-11-30 22:42:35 +00003837
3838 return Owned(MemExpr);
3839 }
3840
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003841 assert(R.isSingleResult());
John McCall161755a2010-04-06 21:38:20 +00003842 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall129e2df2009-11-30 22:42:35 +00003843 NamedDecl *MemberDecl = R.getFoundDecl();
3844
3845 // FIXME: diagnose the presence of template arguments now.
3846
3847 // If the decl being referenced had an error, return an error for this
3848 // sub-expr without emitting another error, in order to avoid cascading
3849 // error cases.
3850 if (MemberDecl->isInvalidDecl())
3851 return ExprError();
3852
John McCallaa81e162009-12-01 22:10:20 +00003853 // Handle the implicit-member-access case.
3854 if (!BaseExpr) {
3855 // If this is not an instance member, convert to a non-member access.
John McCall161755a2010-04-06 21:38:20 +00003856 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnara25777432010-08-11 22:01:17 +00003857 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCallaa81e162009-12-01 22:10:20 +00003858
Douglas Gregor828a1972010-01-07 23:12:05 +00003859 SourceLocation Loc = R.getNameLoc();
3860 if (SS.getRange().isValid())
3861 Loc = SS.getRange().getBegin();
3862 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003863 }
3864
John McCall129e2df2009-11-30 22:42:35 +00003865 bool ShouldCheckUse = true;
3866 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3867 // Don't diagnose the use of a virtual member function unless it's
3868 // explicitly qualified.
3869 if (MD->isVirtual() && !SS.isSet())
3870 ShouldCheckUse = false;
3871 }
3872
3873 // Check the use of this member.
3874 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3875 Owned(BaseExpr);
3876 return ExprError();
3877 }
3878
John McCallf6a16482010-12-04 03:47:34 +00003879 // Perform a property load on the base regardless of whether we
3880 // actually need it for the declaration.
John Wiegley429bb272011-04-08 18:41:53 +00003881 if (BaseExpr->getObjectKind() == OK_ObjCProperty) {
3882 ExprResult Result = ConvertPropertyForRValue(BaseExpr);
3883 if (Result.isInvalid())
3884 return ExprError();
3885 BaseExpr = Result.take();
3886 }
John McCallf6a16482010-12-04 03:47:34 +00003887
John McCalldfa1edb2010-11-23 20:48:44 +00003888 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3889 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3890 SS, FD, FoundDecl, MemberNameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003891
Francois Pichet87c2e122010-11-21 06:08:52 +00003892 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3893 // We may have found a field within an anonymous union or struct
3894 // (C++ [class.union]).
John McCall5808ce42011-02-03 08:15:49 +00003895 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCallf6a16482010-12-04 03:47:34 +00003896 BaseExpr, OpLoc);
Francois Pichet87c2e122010-11-21 06:08:52 +00003897
John McCall129e2df2009-11-30 22:42:35 +00003898 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3899 MarkDeclarationReferenced(MemberLoc, Var);
3900 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003901 Var, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003902 Var->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00003903 VK_LValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003904 }
3905
John McCallf89e55a2010-11-18 06:31:45 +00003906 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall129e2df2009-11-30 22:42:35 +00003907 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3908 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003909 MemberFn, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003910 MemberFn->getType(),
3911 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3912 OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003913 }
John McCallf89e55a2010-11-18 06:31:45 +00003914 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall129e2df2009-11-30 22:42:35 +00003915
3916 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3917 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3918 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003919 Enum, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003920 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003921 }
3922
3923 Owned(BaseExpr);
3924
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003925 // We found something that we didn't expect. Complain.
John McCall129e2df2009-11-30 22:42:35 +00003926 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnara25777432010-08-11 22:01:17 +00003927 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003928 << MemberName << BaseType << int(IsArrow);
3929 else
3930 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3931 << MemberName << BaseType << int(IsArrow);
John McCall129e2df2009-11-30 22:42:35 +00003932
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003933 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3934 << MemberName;
Douglas Gregor2b147f02010-04-25 21:15:30 +00003935 R.suppressDiagnostics();
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003936 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00003937}
3938
John McCall028d3972010-12-15 16:46:44 +00003939/// Given that normal member access failed on the given expression,
3940/// and given that the expression's type involves builtin-id or
3941/// builtin-Class, decide whether substituting in the redefinition
3942/// types would be profitable. The redefinition type is whatever
3943/// this translation unit tried to typedef to id/Class; we store
3944/// it to the side and then re-use it in places like this.
John Wiegley429bb272011-04-08 18:41:53 +00003945static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
John McCall028d3972010-12-15 16:46:44 +00003946 const ObjCObjectPointerType *opty
John Wiegley429bb272011-04-08 18:41:53 +00003947 = base.get()->getType()->getAs<ObjCObjectPointerType>();
John McCall028d3972010-12-15 16:46:44 +00003948 if (!opty) return false;
3949
3950 const ObjCObjectType *ty = opty->getObjectType();
3951
3952 QualType redef;
3953 if (ty->isObjCId()) {
3954 redef = S.Context.ObjCIdRedefinitionType;
3955 } else if (ty->isObjCClass()) {
3956 redef = S.Context.ObjCClassRedefinitionType;
3957 } else {
3958 return false;
3959 }
3960
3961 // Do the substitution as long as the redefinition type isn't just a
3962 // possibly-qualified pointer to builtin-id or builtin-Class again.
3963 opty = redef->getAs<ObjCObjectPointerType>();
3964 if (opty && !opty->getObjectType()->getInterface() != 0)
3965 return false;
3966
John Wiegley429bb272011-04-08 18:41:53 +00003967 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
John McCall028d3972010-12-15 16:46:44 +00003968 return true;
3969}
3970
John McCall129e2df2009-11-30 22:42:35 +00003971/// Look up the given member of the given non-type-dependent
3972/// expression. This can return in one of two ways:
3973/// * If it returns a sentinel null-but-valid result, the caller will
3974/// assume that lookup was performed and the results written into
3975/// the provided structure. It will take over from there.
3976/// * Otherwise, the returned expression will be produced in place of
3977/// an ordinary member expression.
3978///
3979/// The ObjCImpDecl bit is a gross hack that will need to be properly
3980/// fixed for ObjC++.
John McCall60d7b3a2010-08-24 06:29:42 +00003981ExprResult
John Wiegley429bb272011-04-08 18:41:53 +00003982Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00003983 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003984 CXXScopeSpec &SS,
John McCalld226f652010-08-21 09:40:31 +00003985 Decl *ObjCImpDecl, bool HasTemplateArgs) {
John Wiegley429bb272011-04-08 18:41:53 +00003986 assert(BaseExpr.get() && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003987
Steve Naroff3cc4af82007-12-16 21:42:28 +00003988 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003989 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003990
John Wiegley429bb272011-04-08 18:41:53 +00003991 if (IsArrow) {
3992 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
3993 if (BaseExpr.isInvalid())
3994 return ExprError();
3995 }
3996
3997 QualType BaseType = BaseExpr.get()->getType();
John McCall129e2df2009-11-30 22:42:35 +00003998 assert(!BaseType->isDependentType());
3999
4000 DeclarationName MemberName = R.getLookupName();
4001 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00004002
John McCall028d3972010-12-15 16:46:44 +00004003 // For later type-checking purposes, turn arrow accesses into dot
4004 // accesses. The only access type we support that doesn't follow
4005 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
4006 // and those never use arrows, so this is unaffected.
4007 if (IsArrow) {
4008 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4009 BaseType = Ptr->getPointeeType();
4010 else if (const ObjCObjectPointerType *Ptr
4011 = BaseType->getAs<ObjCObjectPointerType>())
4012 BaseType = Ptr->getPointeeType();
4013 else if (BaseType->isRecordType()) {
4014 // Recover from arrow accesses to records, e.g.:
4015 // struct MyRecord foo;
4016 // foo->bar
4017 // This is actually well-formed in C++ if MyRecord has an
4018 // overloaded operator->, but that should have been dealt with
4019 // by now.
4020 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley429bb272011-04-08 18:41:53 +00004021 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
John McCall028d3972010-12-15 16:46:44 +00004022 << FixItHint::CreateReplacement(OpLoc, ".");
4023 IsArrow = false;
4024 } else {
4025 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
John Wiegley429bb272011-04-08 18:41:53 +00004026 << BaseType << BaseExpr.get()->getSourceRange();
John McCall028d3972010-12-15 16:46:44 +00004027 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00004028 }
4029 }
4030
John McCall028d3972010-12-15 16:46:44 +00004031 // Handle field access to simple records.
4032 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John Wiegley429bb272011-04-08 18:41:53 +00004033 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
John McCall028d3972010-12-15 16:46:44 +00004034 RTy, OpLoc, SS, HasTemplateArgs))
4035 return ExprError();
4036
4037 // Returning valid-but-null is how we indicate to the caller that
4038 // the lookup result was filled in.
4039 return Owned((Expr*) 0);
David Chisnall0f436562009-08-17 16:35:33 +00004040 }
John McCall129e2df2009-11-30 22:42:35 +00004041
John McCall028d3972010-12-15 16:46:44 +00004042 // Handle ivar access to Objective-C objects.
4043 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004044 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall028d3972010-12-15 16:46:44 +00004045
4046 // There are three cases for the base type:
4047 // - builtin id (qualified or unqualified)
4048 // - builtin Class (qualified or unqualified)
4049 // - an interface
4050 ObjCInterfaceDecl *IDecl = OTy->getInterface();
4051 if (!IDecl) {
4052 // There's an implicit 'isa' ivar on all objects.
4053 // But we only actually find it this way on objects of type 'id',
4054 // apparently.
4055 if (OTy->isObjCId() && Member->isStr("isa"))
John Wiegley429bb272011-04-08 18:41:53 +00004056 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
John McCall028d3972010-12-15 16:46:44 +00004057 Context.getObjCClassType()));
4058
4059 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4060 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4061 ObjCImpDecl, HasTemplateArgs);
4062 goto fail;
4063 }
4064
4065 ObjCInterfaceDecl *ClassDeclared;
4066 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
4067
4068 if (!IV) {
4069 // Attempt to correct for typos in ivar names.
4070 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
4071 LookupMemberName);
4072 if (CorrectTypo(Res, 0, 0, IDecl, false,
4073 IsArrow ? CTC_ObjCIvarLookup
4074 : CTC_ObjCPropertyLookup) &&
4075 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
4076 Diag(R.getNameLoc(),
4077 diag::err_typecheck_member_reference_ivar_suggest)
4078 << IDecl->getDeclName() << MemberName << IV->getDeclName()
4079 << FixItHint::CreateReplacement(R.getNameLoc(),
4080 IV->getNameAsString());
4081 Diag(IV->getLocation(), diag::note_previous_decl)
4082 << IV->getDeclName();
4083 } else {
4084 Res.clear();
4085 Res.setLookupName(Member);
4086
4087 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
4088 << IDecl->getDeclName() << MemberName
John Wiegley429bb272011-04-08 18:41:53 +00004089 << BaseExpr.get()->getSourceRange();
John McCall028d3972010-12-15 16:46:44 +00004090 return ExprError();
4091 }
4092 }
4093
4094 // If the decl being referenced had an error, return an error for this
4095 // sub-expr without emitting another error, in order to avoid cascading
4096 // error cases.
4097 if (IV->isInvalidDecl())
4098 return ExprError();
4099
4100 // Check whether we can reference this field.
4101 if (DiagnoseUseOfDecl(IV, MemberLoc))
4102 return ExprError();
4103 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
4104 IV->getAccessControl() != ObjCIvarDecl::Package) {
4105 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
4106 if (ObjCMethodDecl *MD = getCurMethodDecl())
4107 ClassOfMethodDecl = MD->getClassInterface();
4108 else if (ObjCImpDecl && getCurFunctionDecl()) {
4109 // Case of a c-function declared inside an objc implementation.
4110 // FIXME: For a c-style function nested inside an objc implementation
4111 // class, there is no implementation context available, so we pass
4112 // down the context as argument to this routine. Ideally, this context
4113 // need be passed down in the AST node and somehow calculated from the
4114 // AST for a function decl.
4115 if (ObjCImplementationDecl *IMPD =
4116 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
4117 ClassOfMethodDecl = IMPD->getClassInterface();
4118 else if (ObjCCategoryImplDecl* CatImplClass =
4119 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
4120 ClassOfMethodDecl = CatImplClass->getClassInterface();
4121 }
4122
4123 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
4124 if (ClassDeclared != IDecl ||
4125 ClassOfMethodDecl != ClassDeclared)
4126 Diag(MemberLoc, diag::error_private_ivar_access)
4127 << IV->getDeclName();
4128 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
4129 // @protected
4130 Diag(MemberLoc, diag::error_protected_ivar_access)
4131 << IV->getDeclName();
4132 }
4133
4134 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
John Wiegley429bb272011-04-08 18:41:53 +00004135 MemberLoc, BaseExpr.take(),
John McCall028d3972010-12-15 16:46:44 +00004136 IsArrow));
4137 }
4138
4139 // Objective-C property access.
4140 const ObjCObjectPointerType *OPT;
4141 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
4142 // This actually uses the base as an r-value.
John Wiegley429bb272011-04-08 18:41:53 +00004143 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4144 if (BaseExpr.isInvalid())
4145 return ExprError();
4146
4147 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
John McCall028d3972010-12-15 16:46:44 +00004148
4149 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
4150
4151 const ObjCObjectType *OT = OPT->getObjectType();
4152
4153 // id, with and without qualifiers.
4154 if (OT->isObjCId()) {
4155 // Check protocols on qualified interfaces.
4156 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
4157 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
4158 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
4159 // Check the use of this declaration
4160 if (DiagnoseUseOfDecl(PD, MemberLoc))
4161 return ExprError();
4162
4163 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
4164 VK_LValue,
4165 OK_ObjCProperty,
4166 MemberLoc,
John Wiegley429bb272011-04-08 18:41:53 +00004167 BaseExpr.take()));
John McCall028d3972010-12-15 16:46:44 +00004168 }
4169
4170 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
4171 // Check the use of this method.
4172 if (DiagnoseUseOfDecl(OMD, MemberLoc))
4173 return ExprError();
4174 Selector SetterSel =
4175 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4176 PP.getSelectorTable(), Member);
4177 ObjCMethodDecl *SMD = 0;
4178 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
4179 SetterSel, Context))
4180 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
4181 QualType PType = OMD->getSendResultType();
4182
4183 ExprValueKind VK = VK_LValue;
4184 if (!getLangOptions().CPlusPlus &&
4185 IsCForbiddenLValueType(Context, PType))
4186 VK = VK_RValue;
4187 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4188
4189 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
4190 VK, OK,
John Wiegley429bb272011-04-08 18:41:53 +00004191 MemberLoc, BaseExpr.take()));
John McCall028d3972010-12-15 16:46:44 +00004192 }
4193 }
Fariborz Jahanian4eb7f692011-03-15 17:27:48 +00004194 // Use of id.member can only be for a property reference. Do not
4195 // use the 'id' redefinition in this case.
4196 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
John McCall028d3972010-12-15 16:46:44 +00004197 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4198 ObjCImpDecl, HasTemplateArgs);
4199
4200 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
4201 << MemberName << BaseType);
4202 }
4203
4204 // 'Class', unqualified only.
4205 if (OT->isObjCClass()) {
4206 // Only works in a method declaration (??!).
4207 ObjCMethodDecl *MD = getCurMethodDecl();
4208 if (!MD) {
4209 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4210 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4211 ObjCImpDecl, HasTemplateArgs);
4212
4213 goto fail;
4214 }
4215
4216 // Also must look for a getter name which uses property syntax.
4217 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004218 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4219 ObjCMethodDecl *Getter;
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004220 if ((Getter = IFace->lookupClassMethod(Sel))) {
4221 // Check the use of this method.
4222 if (DiagnoseUseOfDecl(Getter, MemberLoc))
4223 return ExprError();
John McCall028d3972010-12-15 16:46:44 +00004224 } else
Fariborz Jahanian74b27562010-12-03 23:37:08 +00004225 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004226 // If we found a getter then this may be a valid dot-reference, we
4227 // will look for the matching setter, in case it is needed.
4228 Selector SetterSel =
John McCall028d3972010-12-15 16:46:44 +00004229 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4230 PP.getSelectorTable(), Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004231 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
4232 if (!Setter) {
4233 // If this reference is in an @implementation, also check for 'private'
4234 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00004235 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004236 }
4237 // Look through local category implementations associated with the class.
4238 if (!Setter)
4239 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004240
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004241 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
4242 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004243
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004244 if (Getter || Setter) {
4245 QualType PType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004246
John McCall09431682010-11-18 19:01:18 +00004247 ExprValueKind VK = VK_LValue;
4248 if (Getter) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004249 PType = Getter->getSendResultType();
John McCall09431682010-11-18 19:01:18 +00004250 if (!getLangOptions().CPlusPlus &&
4251 IsCForbiddenLValueType(Context, PType))
4252 VK = VK_RValue;
4253 } else {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004254 // Get the expression type from Setter's incoming parameter.
4255 PType = (*(Setter->param_end() -1))->getType();
John McCall09431682010-11-18 19:01:18 +00004256 }
4257 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4258
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004259 // FIXME: we must check that the setter has property type.
John McCall12f78a62010-12-02 01:19:52 +00004260 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
4261 PType, VK, OK,
John Wiegley429bb272011-04-08 18:41:53 +00004262 MemberLoc, BaseExpr.take()));
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004263 }
John McCall028d3972010-12-15 16:46:44 +00004264
4265 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4266 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4267 ObjCImpDecl, HasTemplateArgs);
4268
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004269 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall028d3972010-12-15 16:46:44 +00004270 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00004271 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004272
John McCall028d3972010-12-15 16:46:44 +00004273 // Normal property access.
John Wiegley429bb272011-04-08 18:41:53 +00004274 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), MemberName, MemberLoc,
John McCall028d3972010-12-15 16:46:44 +00004275 SourceLocation(), QualType(), false);
Steve Naroff14108da2009-07-10 23:34:53 +00004276 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004277
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004278 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00004279 if (BaseType->isExtVectorType()) {
John McCall5e3c67b2010-12-15 04:42:30 +00004280 // FIXME: this expr should store IsArrow.
Anders Carlsson8f28f992009-08-26 18:25:21 +00004281 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John Wiegley429bb272011-04-08 18:41:53 +00004282 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
John McCall09431682010-11-18 19:01:18 +00004283 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
4284 Member, MemberLoc);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004285 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004286 return ExprError();
John McCall09431682010-11-18 19:01:18 +00004287
John Wiegley429bb272011-04-08 18:41:53 +00004288 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
John McCall09431682010-11-18 19:01:18 +00004289 *Member, MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004290 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004291
John McCall028d3972010-12-15 16:46:44 +00004292 // Adjust builtin-sel to the appropriate redefinition type if that's
4293 // not just a pointer to builtin-sel again.
4294 if (IsArrow &&
4295 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4296 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004297 BaseExpr = ImpCastExprToType(BaseExpr.take(), Context.ObjCSelRedefinitionType,
4298 CK_BitCast);
John McCall028d3972010-12-15 16:46:44 +00004299 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4300 ObjCImpDecl, HasTemplateArgs);
4301 }
4302
4303 // Failure cases.
4304 fail:
4305
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004306 // Recover from dot accesses to pointers, e.g.:
4307 // type *foo;
4308 // foo.bar
4309 // This is actually well-formed in two cases:
4310 // - 'type' is an Objective C type
4311 // - 'bar' is a pseudo-destructor name which happens to refer to
4312 // the appropriate pointer type
John McCall028d3972010-12-15 16:46:44 +00004313 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004314 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4315 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall028d3972010-12-15 16:46:44 +00004316 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley429bb272011-04-08 18:41:53 +00004317 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004318 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall028d3972010-12-15 16:46:44 +00004319
4320 // Recurse as an -> access.
4321 IsArrow = true;
4322 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4323 ObjCImpDecl, HasTemplateArgs);
4324 }
John McCall028d3972010-12-15 16:46:44 +00004325 }
4326
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004327 // If the user is trying to apply -> or . to a function name, it's probably
4328 // because they forgot parentheses to call that function.
4329 bool TryCall = false;
4330 bool Overloaded = false;
4331 UnresolvedSet<8> AllOverloads;
John Wiegley429bb272011-04-08 18:41:53 +00004332 if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(BaseExpr.get())) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004333 AllOverloads.append(Overloads->decls_begin(), Overloads->decls_end());
4334 TryCall = true;
4335 Overloaded = true;
John Wiegley429bb272011-04-08 18:41:53 +00004336 } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(BaseExpr.get())) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004337 if (FunctionDecl* Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
4338 AllOverloads.addDecl(Fun);
4339 TryCall = true;
4340 }
4341 }
John McCall028d3972010-12-15 16:46:44 +00004342
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004343 if (TryCall) {
4344 // Plunder the overload set for something that would make the member
4345 // expression valid.
4346 UnresolvedSet<4> ViableOverloads;
4347 bool HasViableZeroArgOverload = false;
4348 for (OverloadExpr::decls_iterator it = AllOverloads.begin(),
4349 DeclsEnd = AllOverloads.end(); it != DeclsEnd; ++it) {
Matt Beaumont-Gayfbe59942011-03-05 02:42:30 +00004350 // Our overload set may include TemplateDecls, which we'll ignore for the
4351 // purposes of determining whether we can issue a '()' fixit.
4352 if (const FunctionDecl *OverloadDecl = dyn_cast<FunctionDecl>(*it)) {
4353 QualType ResultTy = OverloadDecl->getResultType();
4354 if ((!IsArrow && ResultTy->isRecordType()) ||
4355 (IsArrow && ResultTy->isPointerType() &&
4356 ResultTy->getPointeeType()->isRecordType())) {
4357 ViableOverloads.addDecl(*it);
4358 if (OverloadDecl->getMinRequiredArguments() == 0) {
4359 HasViableZeroArgOverload = true;
4360 }
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004361 }
John McCall028d3972010-12-15 16:46:44 +00004362 }
4363 }
4364
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004365 if (!HasViableZeroArgOverload || ViableOverloads.size() != 1) {
John Wiegley429bb272011-04-08 18:41:53 +00004366 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gayfbe59942011-03-05 02:42:30 +00004367 << (AllOverloads.size() > 1) << 0
John Wiegley429bb272011-04-08 18:41:53 +00004368 << BaseExpr.get()->getSourceRange();
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004369 int ViableOverloadCount = ViableOverloads.size();
4370 int I;
4371 for (I = 0; I < ViableOverloadCount; ++I) {
4372 // FIXME: Magic number for max shown overloads stolen from
4373 // OverloadCandidateSet::NoteCandidates.
4374 if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
4375 break;
4376 }
4377 Diag(ViableOverloads[I].getDecl()->getSourceRange().getBegin(),
4378 diag::note_member_ref_possible_intended_overload);
4379 }
4380 if (I != ViableOverloadCount) {
John Wiegley429bb272011-04-08 18:41:53 +00004381 Diag(BaseExpr.get()->getExprLoc(), diag::note_ovl_too_many_candidates)
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004382 << int(ViableOverloadCount - I);
4383 }
4384 return ExprError();
4385 }
4386 } else {
4387 // We don't have an expression that's convenient to get a Decl from, but we
4388 // can at least check if the type is "function of 0 arguments which returns
4389 // an acceptable type".
4390 const FunctionType *Fun = NULL;
4391 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4392 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4393 TryCall = true;
4394 }
4395 } else if ((Fun = BaseType->getAs<FunctionType>())) {
4396 TryCall = true;
4397 }
John McCall028d3972010-12-15 16:46:44 +00004398
4399 if (TryCall) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004400 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4401 if (FPT->getNumArgs() == 0) {
4402 QualType ResultTy = Fun->getResultType();
4403 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4404 (IsArrow && ResultTy->isPointerType() &&
4405 ResultTy->getPointeeType()->isRecordType());
4406 }
Matt Beaumont-Gay26ae5dd2011-02-17 02:54:17 +00004407 }
John McCall028d3972010-12-15 16:46:44 +00004408 }
4409 }
4410
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004411 if (TryCall) {
4412 // At this point, we know BaseExpr looks like it's potentially callable with
4413 // 0 arguments, and that it returns something of a reasonable type, so we
4414 // can emit a fixit and carry on pretending that BaseExpr was actually a
4415 // CallExpr.
4416 SourceLocation ParenInsertionLoc =
John Wiegley429bb272011-04-08 18:41:53 +00004417 PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
4418 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004419 << int(Overloaded) << 1
John Wiegley429bb272011-04-08 18:41:53 +00004420 << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004421 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
John Wiegley429bb272011-04-08 18:41:53 +00004422 ExprResult NewBase = ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004423 MultiExprArg(*this, 0, 0),
4424 ParenInsertionLoc);
4425 if (NewBase.isInvalid())
4426 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004427 BaseExpr = NewBase;
4428 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004429 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4430 ObjCImpDecl, HasTemplateArgs);
4431 }
4432
Douglas Gregor214f31a2009-03-27 06:00:30 +00004433 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
John Wiegley429bb272011-04-08 18:41:53 +00004434 << BaseType << BaseExpr.get()->getSourceRange();
Douglas Gregor214f31a2009-03-27 06:00:30 +00004435
Douglas Gregor214f31a2009-03-27 06:00:30 +00004436 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00004437}
4438
John McCall129e2df2009-11-30 22:42:35 +00004439/// The main callback when the parser finds something like
4440/// expression . [nested-name-specifier] identifier
4441/// expression -> [nested-name-specifier] identifier
4442/// where 'identifier' encompasses a fairly broad spectrum of
4443/// possibilities, including destructor and operator references.
4444///
4445/// \param OpKind either tok::arrow or tok::period
4446/// \param HasTrailingLParen whether the next token is '(', which
4447/// is used to diagnose mis-uses of special members that can
4448/// only be called
4449/// \param ObjCImpDecl the current ObjC @implementation decl;
4450/// this is an ugly hack around the fact that ObjC @implementations
4451/// aren't properly put in the context chain
John McCall60d7b3a2010-08-24 06:29:42 +00004452ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall5e3c67b2010-12-15 04:42:30 +00004453 SourceLocation OpLoc,
4454 tok::TokenKind OpKind,
4455 CXXScopeSpec &SS,
4456 UnqualifiedId &Id,
4457 Decl *ObjCImpDecl,
4458 bool HasTrailingLParen) {
John McCall129e2df2009-11-30 22:42:35 +00004459 if (SS.isSet() && SS.isInvalid())
4460 return ExprError();
4461
Francois Pichetdbee3412011-01-18 05:04:39 +00004462 // Warn about the explicit constructor calls Microsoft extension.
4463 if (getLangOptions().Microsoft &&
4464 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4465 Diag(Id.getSourceRange().getBegin(),
4466 diag::ext_ms_explicit_constructor_call);
4467
John McCall129e2df2009-11-30 22:42:35 +00004468 TemplateArgumentListInfo TemplateArgsBuffer;
4469
4470 // Decompose the name into its component parts.
Abramo Bagnara25777432010-08-11 22:01:17 +00004471 DeclarationNameInfo NameInfo;
John McCall129e2df2009-11-30 22:42:35 +00004472 const TemplateArgumentListInfo *TemplateArgs;
4473 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00004474 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004475
Abramo Bagnara25777432010-08-11 22:01:17 +00004476 DeclarationName Name = NameInfo.getName();
John McCall129e2df2009-11-30 22:42:35 +00004477 bool IsArrow = (OpKind == tok::arrow);
4478
4479 NamedDecl *FirstQualifierInScope
4480 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4481 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4482
4483 // This is a postfix expression, so get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004484 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004485 if (Result.isInvalid()) return ExprError();
4486 Base = Result.take();
John McCall129e2df2009-11-30 22:42:35 +00004487
Douglas Gregor01e56ae2010-04-12 20:54:26 +00004488 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4489 isDependentScopeSpecifier(SS)) {
John McCall9ae2f072010-08-23 23:25:46 +00004490 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00004491 IsArrow, OpLoc,
4492 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00004493 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004494 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00004495 LookupResult R(*this, NameInfo, LookupMemberName);
John Wiegley429bb272011-04-08 18:41:53 +00004496 ExprResult BaseResult = Owned(Base);
4497 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCallad00b772010-06-16 08:42:20 +00004498 SS, ObjCImpDecl, TemplateArgs != 0);
John Wiegley429bb272011-04-08 18:41:53 +00004499 if (BaseResult.isInvalid())
4500 return ExprError();
4501 Base = BaseResult.take();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004502
John McCallad00b772010-06-16 08:42:20 +00004503 if (Result.isInvalid()) {
4504 Owned(Base);
4505 return ExprError();
4506 }
John McCall129e2df2009-11-30 22:42:35 +00004507
John McCallad00b772010-06-16 08:42:20 +00004508 if (Result.get()) {
4509 // The only way a reference to a destructor can be used is to
4510 // immediately call it, which falls into this case. If the
4511 // next token is not a '(', produce a diagnostic and build the
4512 // call now.
4513 if (!HasTrailingLParen &&
4514 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCall9ae2f072010-08-23 23:25:46 +00004515 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall129e2df2009-11-30 22:42:35 +00004516
John McCallad00b772010-06-16 08:42:20 +00004517 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00004518 }
4519
John McCall9ae2f072010-08-23 23:25:46 +00004520 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00004521 OpLoc, IsArrow, SS, FirstQualifierInScope,
4522 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004523 }
4524
4525 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00004526}
4527
John McCall60d7b3a2010-08-24 06:29:42 +00004528ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00004529 FunctionDecl *FD,
4530 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00004531 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004532 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00004533 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00004534 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00004535 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00004536 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004537 return ExprError();
4538 }
4539
4540 if (Param->hasUninstantiatedDefaultArg()) {
4541 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00004542
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004543 // Instantiate the expression.
4544 MultiLevelTemplateArgumentList ArgList
4545 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00004546
Nico Weber08e41a62010-11-29 18:19:25 +00004547 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004548 = ArgList.getInnermost();
4549 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4550 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004551
Nico Weber08e41a62010-11-29 18:19:25 +00004552 ExprResult Result;
4553 {
4554 // C++ [dcl.fct.default]p5:
4555 // The names in the [default argument] expression are bound, and
4556 // the semantic constraints are checked, at the point where the
4557 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00004558 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00004559 Result = SubstExpr(UninstExpr, ArgList);
4560 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004561 if (Result.isInvalid())
4562 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004563
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004564 // Check the expression as an initializer for the parameter.
4565 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004566 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004567 InitializationKind Kind
4568 = InitializationKind::CreateCopy(Param->getLocation(),
4569 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4570 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00004571
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004572 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4573 Result = InitSeq.Perform(*this, Entity, Kind,
4574 MultiExprArg(*this, &ResultE, 1));
4575 if (Result.isInvalid())
4576 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004577
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004578 // Build the default argument expression.
4579 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4580 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004581 }
4582
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004583 // If the default expression creates temporaries, we need to
4584 // push them to the current stack of expression temporaries so they'll
4585 // be properly destroyed.
4586 // FIXME: We should really be rebuilding the default argument with new
4587 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00004588 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4589 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4590 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4591 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4592 ExprTemporaries.push_back(Temporary);
4593 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004594
4595 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00004596 // Just mark all of the declarations in this potentially-evaluated expression
4597 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004598 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00004599 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004600}
4601
Douglas Gregor88a35142008-12-22 05:46:06 +00004602/// ConvertArgumentsForCall - Converts the arguments specified in
4603/// Args/NumArgs to the parameter types of the function FDecl with
4604/// function prototype Proto. Call is the call expression itself, and
4605/// Fn is the function expression. For a C++ member function, this
4606/// routine does not attempt to convert the object argument. Returns
4607/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004608bool
4609Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00004610 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00004611 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00004612 Expr **Args, unsigned NumArgs,
4613 SourceLocation RParenLoc) {
John McCall8e10f3b2011-02-26 05:39:39 +00004614 // Bail out early if calling a builtin with custom typechecking.
4615 // We don't need to do this in the
4616 if (FDecl)
4617 if (unsigned ID = FDecl->getBuiltinID())
4618 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4619 return false;
4620
Mike Stumpeed9cac2009-02-19 03:04:26 +00004621 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00004622 // assignment, to the types of the corresponding parameter, ...
4623 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004624 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004625
Douglas Gregor88a35142008-12-22 05:46:06 +00004626 // If too few arguments are available (and we don't have default
4627 // arguments for the remaining parameters), don't make the call.
4628 if (NumArgs < NumArgsInProto) {
4629 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4630 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004631 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00004632 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00004633 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00004634 }
4635
4636 // If too many are passed and not variadic, error on the extras and drop
4637 // them.
4638 if (NumArgs > NumArgsInProto) {
4639 if (!Proto->isVariadic()) {
4640 Diag(Args[NumArgsInProto]->getLocStart(),
4641 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004642 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00004643 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00004644 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4645 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00004646
4647 // Emit the location of the prototype.
4648 if (FDecl && !FDecl->getBuiltinID())
4649 Diag(FDecl->getLocStart(),
4650 diag::note_typecheck_call_too_many_args)
4651 << FDecl;
4652
Douglas Gregor88a35142008-12-22 05:46:06 +00004653 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004654 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004655 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004656 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004657 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004658 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004659 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004660 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4661 if (Fn->getType()->isBlockPointerType())
4662 CallType = VariadicBlock; // Block
4663 else if (isa<MemberExpr>(Fn))
4664 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004665 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004666 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004667 if (Invalid)
4668 return true;
4669 unsigned TotalNumArgs = AllArgs.size();
4670 for (unsigned i = 0; i < TotalNumArgs; ++i)
4671 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004672
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004673 return false;
4674}
Mike Stumpeed9cac2009-02-19 03:04:26 +00004675
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004676bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4677 FunctionDecl *FDecl,
4678 const FunctionProtoType *Proto,
4679 unsigned FirstProtoArg,
4680 Expr **Args, unsigned NumArgs,
4681 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004682 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004683 unsigned NumArgsInProto = Proto->getNumArgs();
4684 unsigned NumArgsToCheck = NumArgs;
4685 bool Invalid = false;
4686 if (NumArgs != NumArgsInProto)
4687 // Use default arguments for missing arguments
4688 NumArgsToCheck = NumArgsInProto;
4689 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00004690 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004691 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004692 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004693
Douglas Gregor88a35142008-12-22 05:46:06 +00004694 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004695 if (ArgIx < NumArgs) {
4696 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004697
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004698 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4699 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004700 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004701 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004702 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004703
Douglas Gregora188ff22009-12-22 16:09:06 +00004704 // Pass the argument
4705 ParmVarDecl *Param = 0;
4706 if (FDecl && i < FDecl->getNumParams())
4707 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00004708
Douglas Gregora188ff22009-12-22 16:09:06 +00004709 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004710 Param? InitializedEntity::InitializeParameter(Context, Param)
4711 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCall60d7b3a2010-08-24 06:29:42 +00004712 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00004713 SourceLocation(),
4714 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00004715 if (ArgE.isInvalid())
4716 return true;
4717
4718 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004719 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00004720 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004721
John McCall60d7b3a2010-08-24 06:29:42 +00004722 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004723 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004724 if (ArgExpr.isInvalid())
4725 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004726
Anders Carlsson56c5e332009-08-25 03:49:14 +00004727 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004728 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004729 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004730 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004731
Douglas Gregor88a35142008-12-22 05:46:06 +00004732 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004733 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00004734
4735 // Assume that extern "C" functions with variadic arguments that
4736 // return __unknown_anytype aren't *really* variadic.
4737 if (Proto->getResultType() == Context.UnknownAnyTy &&
4738 FDecl && FDecl->isExternC()) {
4739 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4740 ExprResult arg;
4741 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
4742 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
4743 else
4744 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4745 Invalid |= arg.isInvalid();
4746 AllArgs.push_back(arg.take());
4747 }
4748
4749 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4750 } else {
4751 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4752 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4753 Invalid |= Arg.isInvalid();
4754 AllArgs.push_back(Arg.take());
4755 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004756 }
4757 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004758 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00004759}
4760
John McCall755d8492011-04-12 00:42:48 +00004761/// Given a function expression of unknown-any type, try to rebuild it
4762/// to have a function type.
4763static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4764
Steve Narofff69936d2007-09-16 03:34:24 +00004765/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00004766/// This provides the location of the left/right parens and a list of comma
4767/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00004768ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004769Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004770 MultiExprArg args, SourceLocation RParenLoc,
4771 Expr *ExecConfig) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00004772 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00004773
4774 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004775 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00004776 if (Result.isInvalid()) return ExprError();
4777 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00004778
John McCall9ae2f072010-08-23 23:25:46 +00004779 Expr **Args = args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004780
Douglas Gregor88a35142008-12-22 05:46:06 +00004781 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00004782 // If this is a pseudo-destructor expression, build the call immediately.
4783 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4784 if (NumArgs > 0) {
4785 // Pseudo-destructor calls should not have any arguments.
4786 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00004787 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00004788 SourceRange(Args[0]->getLocStart(),
4789 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00004790
Douglas Gregora71d8192009-09-04 17:36:40 +00004791 NumArgs = 0;
4792 }
Mike Stump1eb44332009-09-09 15:08:12 +00004793
Douglas Gregora71d8192009-09-04 17:36:40 +00004794 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00004795 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00004796 }
Mike Stump1eb44332009-09-09 15:08:12 +00004797
Douglas Gregor17330012009-02-04 15:01:18 +00004798 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00004799 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00004800 // FIXME: Will need to cache the results of name lookup (including ADL) in
4801 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00004802 bool Dependent = false;
4803 if (Fn->isTypeDependent())
4804 Dependent = true;
4805 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4806 Dependent = true;
4807
Peter Collingbournee08ce652011-02-09 21:07:24 +00004808 if (Dependent) {
4809 if (ExecConfig) {
4810 return Owned(new (Context) CUDAKernelCallExpr(
4811 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4812 Context.DependentTy, VK_RValue, RParenLoc));
4813 } else {
4814 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4815 Context.DependentTy, VK_RValue,
4816 RParenLoc));
4817 }
4818 }
Douglas Gregor17330012009-02-04 15:01:18 +00004819
4820 // Determine whether this is a call to an object (C++ [over.call.object]).
4821 if (Fn->getType()->isRecordType())
4822 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004823 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00004824
John McCall755d8492011-04-12 00:42:48 +00004825 if (Fn->getType() == Context.UnknownAnyTy) {
4826 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4827 if (result.isInvalid()) return ExprError();
4828 Fn = result.take();
4829 }
4830
John McCall129e2df2009-11-30 22:42:35 +00004831 Expr *NakedFn = Fn->IgnoreParens();
4832
4833 // Determine whether this is a call to an unresolved member function.
4834 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4835 // If lookup was unresolved but not dependent (i.e. didn't find
4836 // an unresolved using declaration), it has to be an overloaded
4837 // function set, which means it must contain either multiple
4838 // declarations (all methods or method templates) or a single
4839 // method template.
4840 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor2b147f02010-04-25 21:15:30 +00004841 isa<FunctionTemplateDecl>(
4842 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00004843 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00004844
John McCallaa81e162009-12-01 22:10:20 +00004845 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004846 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00004847 }
4848
Douglas Gregorfa047642009-02-04 00:32:51 +00004849 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00004850 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00004851 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00004852 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00004853 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004854 RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00004855 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004856
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004857 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00004858 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCall2de56d12010-08-25 11:45:40 +00004859 if (BO->getOpcode() == BO_PtrMemD ||
4860 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00004861 if (const FunctionProtoType *FPT
4862 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004863 QualType ResultTy = FPT->getCallResultType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00004864 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004865
Douglas Gregorfdc13a02011-02-04 12:57:49 +00004866 // Check that the object type isn't more qualified than the
4867 // member function we're calling.
4868 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4869 Qualifiers ObjectQuals
4870 = BO->getOpcode() == BO_PtrMemD
4871 ? BO->getLHS()->getType().getQualifiers()
4872 : BO->getLHS()->getType()->getAs<PointerType>()
4873 ->getPointeeType().getQualifiers();
4874
4875 Qualifiers Difference = ObjectQuals - FuncQuals;
4876 Difference.removeObjCGCAttr();
4877 Difference.removeAddressSpace();
4878 if (Difference) {
4879 std::string QualsString = Difference.getAsString();
4880 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4881 << BO->getType().getUnqualifiedType()
4882 << QualsString
4883 << (QualsString.find(' ') == std::string::npos? 1 : 2);
4884 }
4885
John McCall9ae2f072010-08-23 23:25:46 +00004886 CXXMemberCallExpr *TheCall
Abramo Bagnara6c572f12010-12-03 21:39:42 +00004887 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCallf89e55a2010-11-18 06:31:45 +00004888 NumArgs, ResultTy, VK,
John McCall9ae2f072010-08-23 23:25:46 +00004889 RParenLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004890
4891 if (CheckCallReturnType(FPT->getResultType(),
4892 BO->getRHS()->getSourceRange().getBegin(),
John McCall9ae2f072010-08-23 23:25:46 +00004893 TheCall, 0))
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004894 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00004895
John McCall9ae2f072010-08-23 23:25:46 +00004896 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004897 RParenLoc))
4898 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004899
John McCall9ae2f072010-08-23 23:25:46 +00004900 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004901 }
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004902 }
4903 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004904 }
4905
Douglas Gregorfa047642009-02-04 00:32:51 +00004906 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00004907 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004908 // lookup and whether there were any explicitly-specified template arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004909
Eli Friedmanefa42f72009-12-26 03:35:45 +00004910 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00004911 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4912 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4913 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004914 RParenLoc, ExecConfig);
Douglas Gregoref9b1492010-11-09 20:03:54 +00004915 }
4916
John McCall3b4294e2009-12-16 12:17:52 +00004917 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00004918 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4919 if (UnOp->getOpcode() == UO_AddrOf)
4920 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4921
John McCall3b4294e2009-12-16 12:17:52 +00004922 if (isa<DeclRefExpr>(NakedFn))
4923 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4924
Peter Collingbournee08ce652011-02-09 21:07:24 +00004925 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4926 ExecConfig);
4927}
4928
4929ExprResult
4930Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4931 MultiExprArg execConfig, SourceLocation GGGLoc) {
4932 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4933 if (!ConfigDecl)
4934 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4935 << "cudaConfigureCall");
4936 QualType ConfigQTy = ConfigDecl->getType();
4937
4938 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4939 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4940
4941 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCallaa81e162009-12-01 22:10:20 +00004942}
4943
John McCall3b4294e2009-12-16 12:17:52 +00004944/// BuildResolvedCallExpr - Build a call to a resolved expression,
4945/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00004946/// unary-convert to an expression of function-pointer or
4947/// block-pointer type.
4948///
4949/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00004950ExprResult
John McCallaa81e162009-12-01 22:10:20 +00004951Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4952 SourceLocation LParenLoc,
4953 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004954 SourceLocation RParenLoc,
4955 Expr *Config) {
John McCallaa81e162009-12-01 22:10:20 +00004956 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4957
Chris Lattner04421082008-04-08 04:40:51 +00004958 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00004959 ExprResult Result = UsualUnaryConversions(Fn);
4960 if (Result.isInvalid())
4961 return ExprError();
4962 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00004963
Chris Lattner925e60d2007-12-28 05:29:59 +00004964 // Make the call expr early, before semantic checks. This guarantees cleanup
4965 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00004966 CallExpr *TheCall;
4967 if (Config) {
4968 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4969 cast<CallExpr>(Config),
4970 Args, NumArgs,
4971 Context.BoolTy,
4972 VK_RValue,
4973 RParenLoc);
4974 } else {
4975 TheCall = new (Context) CallExpr(Context, Fn,
4976 Args, NumArgs,
4977 Context.BoolTy,
4978 VK_RValue,
4979 RParenLoc);
4980 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004981
John McCall8e10f3b2011-02-26 05:39:39 +00004982 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4983
4984 // Bail out early if calling a builtin with custom typechecking.
4985 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4986 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4987
John McCall1de4d4e2011-04-07 08:22:57 +00004988 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00004989 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00004990 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00004991 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4992 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00004993 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00004994 if (FuncT == 0)
4995 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4996 << Fn->getType() << Fn->getSourceRange());
4997 } else if (const BlockPointerType *BPT =
4998 Fn->getType()->getAs<BlockPointerType>()) {
4999 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5000 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00005001 // Handle calls to expressions of unknown-any type.
5002 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00005003 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00005004 if (rewrite.isInvalid()) return ExprError();
5005 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00005006 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00005007 goto retry;
5008 }
5009
Sebastian Redl0eb23302009-01-19 00:08:26 +00005010 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5011 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00005012 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00005013
Peter Collingbourne0423fc62011-02-23 01:53:29 +00005014 if (getLangOptions().CUDA) {
5015 if (Config) {
5016 // CUDA: Kernel calls must be to global functions
5017 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5018 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5019 << FDecl->getName() << Fn->getSourceRange());
5020
5021 // CUDA: Kernel function must have 'void' return type
5022 if (!FuncT->getResultType()->isVoidType())
5023 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5024 << Fn->getType() << Fn->getSourceRange());
5025 }
5026 }
5027
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00005028 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005029 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00005030 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00005031 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00005032 return ExprError();
5033
Chris Lattner925e60d2007-12-28 05:29:59 +00005034 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00005035 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00005036 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00005037
Douglas Gregor72564e72009-02-26 23:50:07 +00005038 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00005039 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00005040 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00005041 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00005042 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00005043 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00005044
Douglas Gregor74734d52009-04-02 15:37:10 +00005045 if (FDecl) {
5046 // Check if we have too few/too many template arguments, based
5047 // on our knowledge of the function definition.
5048 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00005049 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00005050 const FunctionProtoType *Proto
5051 = Def->getType()->getAs<FunctionProtoType>();
5052 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00005053 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5054 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00005055 }
Douglas Gregor46542412010-10-25 20:39:23 +00005056
5057 // If the function we're calling isn't a function prototype, but we have
5058 // a function prototype from a prior declaratiom, use that prototype.
5059 if (!FDecl->hasPrototype())
5060 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00005061 }
5062
Steve Naroffb291ab62007-08-28 23:30:39 +00005063 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00005064 for (unsigned i = 0; i != NumArgs; i++) {
5065 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00005066
5067 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00005068 InitializedEntity Entity
5069 = InitializedEntity::InitializeParameter(Context,
5070 Proto->getArgType(i));
5071 ExprResult ArgE = PerformCopyInitialization(Entity,
5072 SourceLocation(),
5073 Owned(Arg));
5074 if (ArgE.isInvalid())
5075 return true;
5076
5077 Arg = ArgE.takeAs<Expr>();
5078
5079 } else {
John Wiegley429bb272011-04-08 18:41:53 +00005080 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5081
5082 if (ArgE.isInvalid())
5083 return true;
5084
5085 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00005086 }
5087
Douglas Gregor0700bbf2010-10-26 05:45:40 +00005088 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
5089 Arg->getType(),
5090 PDiag(diag::err_call_incomplete_argument)
5091 << Arg->getSourceRange()))
5092 return ExprError();
5093
Chris Lattner925e60d2007-12-28 05:29:59 +00005094 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00005095 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005096 }
Chris Lattner925e60d2007-12-28 05:29:59 +00005097
Douglas Gregor88a35142008-12-22 05:46:06 +00005098 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5099 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005100 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5101 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00005102
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00005103 // Check for sentinels
5104 if (NDecl)
5105 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00005106
Chris Lattner59907c42007-08-10 20:18:51 +00005107 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00005108 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00005109 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00005110 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00005111
John McCall8e10f3b2011-02-26 05:39:39 +00005112 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00005113 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00005114 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00005115 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00005116 return ExprError();
5117 }
Chris Lattner59907c42007-08-10 20:18:51 +00005118
John McCall9ae2f072010-08-23 23:25:46 +00005119 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00005120}
5121
John McCall60d7b3a2010-08-24 06:29:42 +00005122ExprResult
John McCallb3d87482010-08-24 05:47:05 +00005123Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005124 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00005125 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00005126 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00005127 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00005128
5129 TypeSourceInfo *TInfo;
5130 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5131 if (!TInfo)
5132 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5133
John McCall9ae2f072010-08-23 23:25:46 +00005134 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00005135}
5136
John McCall60d7b3a2010-08-24 06:29:42 +00005137ExprResult
John McCall42f56b52010-01-18 19:35:47 +00005138Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00005139 SourceLocation RParenLoc, Expr *literalExpr) {
John McCall42f56b52010-01-18 19:35:47 +00005140 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00005141
Eli Friedman6223c222008-05-20 05:22:08 +00005142 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00005143 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5144 PDiag(diag::err_illegal_decl_array_incomplete_type)
5145 << SourceRange(LParenLoc,
5146 literalExpr->getSourceRange().getEnd())))
5147 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00005148 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005149 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5150 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00005151 } else if (!literalType->isDependentType() &&
5152 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00005153 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005154 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00005155 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005156 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00005157
Douglas Gregor99a2e602009-12-16 01:38:02 +00005158 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00005159 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005160 InitializationKind Kind
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005161 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor99a2e602009-12-16 01:38:02 +00005162 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00005163 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00005164 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00005165 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00005166 &literalType);
5167 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005168 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00005169 literalExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00005170
Chris Lattner371f2582008-12-04 23:50:19 +00005171 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00005172 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00005173 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005174 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00005175 }
Eli Friedman08544622009-12-22 02:35:53 +00005176
John McCallf89e55a2010-11-18 06:31:45 +00005177 // In C, compound literals are l-values for some reason.
5178 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
5179
John McCall1d7d8d62010-01-19 22:33:45 +00005180 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCallf89e55a2010-11-18 06:31:45 +00005181 VK, literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00005182}
5183
John McCall60d7b3a2010-08-24 06:29:42 +00005184ExprResult
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005185Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005186 SourceLocation RBraceLoc) {
5187 unsigned NumInit = initlist.size();
John McCall9ae2f072010-08-23 23:25:46 +00005188 Expr **InitList = initlist.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00005189
Steve Naroff08d92e42007-09-15 18:49:24 +00005190 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00005191 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005192
Ted Kremenek709210f2010-04-13 23:39:13 +00005193 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
5194 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00005195 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005196 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00005197}
5198
John McCallf3ea8cf2010-11-14 08:17:51 +00005199/// Prepares for a scalar cast, performing all the necessary stages
5200/// except the final cast and returning the kind required.
John Wiegley429bb272011-04-08 18:41:53 +00005201static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00005202 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5203 // Also, callers should have filtered out the invalid cases with
5204 // pointers. Everything else should be possible.
5205
John Wiegley429bb272011-04-08 18:41:53 +00005206 QualType SrcTy = Src.get()->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00005207 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00005208 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00005209
John McCalldaa8e4e2010-11-15 09:13:47 +00005210 switch (SrcTy->getScalarTypeKind()) {
5211 case Type::STK_MemberPointer:
5212 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005213
John McCalldaa8e4e2010-11-15 09:13:47 +00005214 case Type::STK_Pointer:
5215 switch (DestTy->getScalarTypeKind()) {
5216 case Type::STK_Pointer:
5217 return DestTy->isObjCObjectPointerType() ?
John McCallf3ea8cf2010-11-14 08:17:51 +00005218 CK_AnyPointerToObjCPointerCast :
5219 CK_BitCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005220 case Type::STK_Bool:
5221 return CK_PointerToBoolean;
5222 case Type::STK_Integral:
5223 return CK_PointerToIntegral;
5224 case Type::STK_Floating:
5225 case Type::STK_FloatingComplex:
5226 case Type::STK_IntegralComplex:
5227 case Type::STK_MemberPointer:
5228 llvm_unreachable("illegal cast from pointer");
5229 }
5230 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005231
John McCalldaa8e4e2010-11-15 09:13:47 +00005232 case Type::STK_Bool: // casting from bool is like casting from an integer
5233 case Type::STK_Integral:
5234 switch (DestTy->getScalarTypeKind()) {
5235 case Type::STK_Pointer:
John Wiegley429bb272011-04-08 18:41:53 +00005236 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00005237 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00005238 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005239 case Type::STK_Bool:
5240 return CK_IntegralToBoolean;
5241 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00005242 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005243 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00005244 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00005245 case Type::STK_IntegralComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005246 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5247 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00005248 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005249 case Type::STK_FloatingComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005250 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5251 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00005252 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005253 case Type::STK_MemberPointer:
5254 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005255 }
5256 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005257
John McCalldaa8e4e2010-11-15 09:13:47 +00005258 case Type::STK_Floating:
5259 switch (DestTy->getScalarTypeKind()) {
5260 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00005261 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005262 case Type::STK_Bool:
5263 return CK_FloatingToBoolean;
5264 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00005265 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00005266 case Type::STK_FloatingComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005267 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5268 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00005269 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005270 case Type::STK_IntegralComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005271 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5272 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00005273 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005274 case Type::STK_Pointer:
5275 llvm_unreachable("valid float->pointer cast?");
5276 case Type::STK_MemberPointer:
5277 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005278 }
5279 break;
5280
John McCalldaa8e4e2010-11-15 09:13:47 +00005281 case Type::STK_FloatingComplex:
5282 switch (DestTy->getScalarTypeKind()) {
5283 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005284 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005285 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005286 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00005287 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005288 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005289 if (S.Context.hasSameType(ET, DestTy))
5290 return CK_FloatingComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00005291 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00005292 return CK_FloatingCast;
5293 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005294 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00005295 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00005296 case Type::STK_Integral:
John Wiegley429bb272011-04-08 18:41:53 +00005297 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5298 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00005299 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00005300 case Type::STK_Pointer:
5301 llvm_unreachable("valid complex float->pointer cast?");
5302 case Type::STK_MemberPointer:
5303 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005304 }
5305 break;
5306
John McCalldaa8e4e2010-11-15 09:13:47 +00005307 case Type::STK_IntegralComplex:
5308 switch (DestTy->getScalarTypeKind()) {
5309 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005310 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005311 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005312 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00005313 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005314 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005315 if (S.Context.hasSameType(ET, DestTy))
5316 return CK_IntegralComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00005317 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00005318 return CK_IntegralCast;
5319 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005320 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00005321 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00005322 case Type::STK_Floating:
John Wiegley429bb272011-04-08 18:41:53 +00005323 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5324 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00005325 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00005326 case Type::STK_Pointer:
5327 llvm_unreachable("valid complex int->pointer cast?");
5328 case Type::STK_MemberPointer:
5329 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005330 }
5331 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00005332 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005333
John McCallf3ea8cf2010-11-14 08:17:51 +00005334 llvm_unreachable("Unhandled scalar cast");
5335 return CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00005336}
5337
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005338/// CheckCastTypes - Check type constraints for casting between types.
John Wiegley429bb272011-04-08 18:41:53 +00005339ExprResult Sema::CheckCastTypes(SourceRange TyR, QualType castType,
5340 Expr *castExpr, CastKind& Kind, ExprValueKind &VK,
5341 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall1de4d4e2011-04-07 08:22:57 +00005342 if (castExpr->getType() == Context.UnknownAnyTy)
5343 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
5344
Sebastian Redl9cc11e72009-07-25 15:41:38 +00005345 if (getLangOptions().CPlusPlus)
Douglas Gregor40749ee2010-11-03 00:35:38 +00005346 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
5347 castExpr->getLocEnd()),
John McCallf89e55a2010-11-18 06:31:45 +00005348 castType, VK, castExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005349 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00005350
John McCallfb8721c2011-04-10 19:13:55 +00005351 assert(!castExpr->getType()->isPlaceholderType());
5352
John McCallf89e55a2010-11-18 06:31:45 +00005353 // We only support r-value casts in C.
5354 VK = VK_RValue;
5355
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005356 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5357 // type needs to be scalar.
5358 if (castType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00005359 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley429bb272011-04-08 18:41:53 +00005360 ExprResult castExprRes = IgnoredValueConversions(castExpr);
5361 if (castExprRes.isInvalid())
5362 return ExprError();
5363 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00005364
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005365 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00005366 Kind = CK_ToVoid;
John Wiegley429bb272011-04-08 18:41:53 +00005367 return Owned(castExpr);
Anders Carlssonebeaf202009-10-16 02:35:04 +00005368 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005369
John Wiegley429bb272011-04-08 18:41:53 +00005370 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
5371 if (castExprRes.isInvalid())
5372 return ExprError();
5373 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00005374
Eli Friedman8d438082010-07-17 20:43:49 +00005375 if (RequireCompleteType(TyR.getBegin(), castType,
5376 diag::err_typecheck_cast_to_incomplete))
John Wiegley429bb272011-04-08 18:41:53 +00005377 return ExprError();
Eli Friedman8d438082010-07-17 20:43:49 +00005378
Anders Carlssonebeaf202009-10-16 02:35:04 +00005379 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00005380 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005381 (castType->isStructureType() || castType->isUnionType())) {
5382 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005383 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005384 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5385 << castType << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005386 Kind = CK_NoOp;
John Wiegley429bb272011-04-08 18:41:53 +00005387 return Owned(castExpr);
Anders Carlssonc3516322009-10-16 02:48:28 +00005388 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005389
Anders Carlssonc3516322009-10-16 02:48:28 +00005390 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005391 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00005392 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005393 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005394 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005395 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005396 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00005397 castExpr->getType()) &&
5398 !Field->isUnnamedBitfield()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005399 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5400 << castExpr->getSourceRange();
5401 break;
5402 }
5403 }
John Wiegley429bb272011-04-08 18:41:53 +00005404 if (Field == FieldEnd) {
5405 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005406 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005407 return ExprError();
5408 }
John McCall2de56d12010-08-25 11:45:40 +00005409 Kind = CK_ToUnion;
John Wiegley429bb272011-04-08 18:41:53 +00005410 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005411 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005412
Anders Carlssonc3516322009-10-16 02:48:28 +00005413 // Reject any other conversions to non-scalar types.
John Wiegley429bb272011-04-08 18:41:53 +00005414 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlssonc3516322009-10-16 02:48:28 +00005415 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005416 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00005417 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005418
John McCallf3ea8cf2010-11-14 08:17:51 +00005419 // The type we're casting to is known to be a scalar or vector.
5420
5421 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005422 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00005423 !castExpr->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005424 Diag(castExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005425 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00005426 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005427 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00005428 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005429
5430 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00005431 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005432
Anton Yartsevd06fea82011-03-27 09:32:40 +00005433 if (castType->isVectorType()) {
5434 if (castType->getAs<VectorType>()->getVectorKind() ==
5435 VectorType::AltiVecVector &&
5436 (castExpr->getType()->isIntegerType() ||
5437 castExpr->getType()->isFloatingType())) {
5438 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00005439 return Owned(castExpr);
5440 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
5441 return ExprError();
Anton Yartsevd06fea82011-03-27 09:32:40 +00005442 } else
John Wiegley429bb272011-04-08 18:41:53 +00005443 return Owned(castExpr);
Anton Yartsevd06fea82011-03-27 09:32:40 +00005444 }
John Wiegley429bb272011-04-08 18:41:53 +00005445 if (castExpr->getType()->isVectorType()) {
5446 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
5447 return ExprError();
5448 else
5449 return Owned(castExpr);
5450 }
Anders Carlssonc3516322009-10-16 02:48:28 +00005451
John McCallf3ea8cf2010-11-14 08:17:51 +00005452 // The source and target types are both scalars, i.e.
5453 // - arithmetic types (fundamental, enum, and complex)
5454 // - all kinds of pointers
5455 // Note that member pointers were filtered out with C++, above.
5456
John Wiegley429bb272011-04-08 18:41:53 +00005457 if (isa<ObjCSelectorExpr>(castExpr)) {
5458 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
5459 return ExprError();
5460 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005461
John McCallf3ea8cf2010-11-14 08:17:51 +00005462 // If either type is a pointer, the other type has to be either an
5463 // integer or a pointer.
Anders Carlssonc3516322009-10-16 02:48:28 +00005464 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00005465 QualType castExprType = castExpr->getType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005466 if (!castExprType->isIntegralType(Context) &&
John Wiegley429bb272011-04-08 18:41:53 +00005467 castExprType->isArithmeticType()) {
5468 Diag(castExpr->getLocStart(),
5469 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00005470 << castExprType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005471 return ExprError();
5472 }
Eli Friedman41826bb2009-05-01 02:23:58 +00005473 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005474 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
5475 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00005476 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005477 return ExprError();
5478 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005479 }
Anders Carlsson82debc72009-10-18 18:12:03 +00005480
John Wiegley429bb272011-04-08 18:41:53 +00005481 castExprRes = Owned(castExpr);
5482 Kind = PrepareScalarCast(*this, castExprRes, castType);
5483 if (castExprRes.isInvalid())
5484 return ExprError();
5485 castExpr = castExprRes.take();
John McCallb7f4ffe2010-08-12 21:44:57 +00005486
John McCallf3ea8cf2010-11-14 08:17:51 +00005487 if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00005488 CheckCastAlign(castExpr, castType, TyR);
5489
John Wiegley429bb272011-04-08 18:41:53 +00005490 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005491}
5492
Anders Carlssonc3516322009-10-16 02:48:28 +00005493bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00005494 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00005495 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005496
Anders Carlssona64db8f2007-11-27 05:51:55 +00005497 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00005498 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00005499 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00005500 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00005501 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005502 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00005503 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005504 } else
5505 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005506 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00005507 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005508
John McCall2de56d12010-08-25 11:45:40 +00005509 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005510 return false;
5511}
5512
John Wiegley429bb272011-04-08 18:41:53 +00005513ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5514 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00005515 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005516
Anders Carlsson16a89042009-10-16 05:23:41 +00005517 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005518
Nate Begeman9b10da62009-06-27 22:05:55 +00005519 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5520 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00005521 if (SrcTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005522 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
5523 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00005524 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00005525 return ExprError();
5526 }
John McCall2de56d12010-08-25 11:45:40 +00005527 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00005528 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00005529 }
5530
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005531 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00005532 // conversion will take place first from scalar to elt type, and then
5533 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005534 if (SrcTy->isPointerType())
5535 return Diag(R.getBegin(),
5536 diag::err_invalid_conversion_between_vector_and_scalar)
5537 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00005538
5539 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00005540 ExprResult CastExprRes = Owned(CastExpr);
5541 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
5542 if (CastExprRes.isInvalid())
5543 return ExprError();
5544 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005545
John McCall2de56d12010-08-25 11:45:40 +00005546 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00005547 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00005548}
5549
John McCall60d7b3a2010-08-24 06:29:42 +00005550ExprResult
John McCallb3d87482010-08-24 05:47:05 +00005551Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005552 SourceLocation RParenLoc, Expr *castExpr) {
5553 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005554 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00005555
John McCall9d125032010-01-15 18:39:57 +00005556 TypeSourceInfo *castTInfo;
5557 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5558 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00005559 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00005560
Nate Begeman2ef13e52009-08-10 23:49:36 +00005561 // If the Expr being casted is a ParenListExpr, handle it specially.
5562 if (isa<ParenListExpr>(castExpr))
John McCall9ae2f072010-08-23 23:25:46 +00005563 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCall42f56b52010-01-18 19:35:47 +00005564 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00005565
John McCall9ae2f072010-08-23 23:25:46 +00005566 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallb042fdf2010-01-15 18:56:44 +00005567}
5568
John McCall60d7b3a2010-08-24 06:29:42 +00005569ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00005570Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005571 SourceLocation RParenLoc, Expr *castExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005572 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00005573 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00005574 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +00005575 ExprResult CastResult =
5576 CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
5577 Kind, VK, BasePath);
5578 if (CastResult.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005579 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00005580 castExpr = CastResult.take();
Anders Carlsson0aebc812009-09-09 21:33:21 +00005581
John McCallf871d0c2010-08-07 06:22:56 +00005582 return Owned(CStyleCastExpr::Create(Context,
John Wiegley429bb272011-04-08 18:41:53 +00005583 Ty->getType().getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +00005584 VK, Kind, castExpr, &BasePath, Ty,
John McCallf871d0c2010-08-07 06:22:56 +00005585 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005586}
5587
Nate Begeman2ef13e52009-08-10 23:49:36 +00005588/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5589/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005590ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005591Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005592 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5593 if (!E)
5594 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00005595
John McCall60d7b3a2010-08-24 06:29:42 +00005596 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00005597
Nate Begeman2ef13e52009-08-10 23:49:36 +00005598 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00005599 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5600 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00005601
John McCall9ae2f072010-08-23 23:25:46 +00005602 if (Result.isInvalid()) return ExprError();
5603
5604 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005605}
5606
John McCall60d7b3a2010-08-24 06:29:42 +00005607ExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00005608Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00005609 SourceLocation RParenLoc, Expr *Op,
John McCall42f56b52010-01-18 19:35:47 +00005610 TypeSourceInfo *TInfo) {
John McCall9ae2f072010-08-23 23:25:46 +00005611 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCall42f56b52010-01-18 19:35:47 +00005612 QualType Ty = TInfo->getType();
Anton Yartsevd06fea82011-03-27 09:32:40 +00005613 bool isVectorLiteral = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005614
Anton Yartsevd06fea82011-03-27 09:32:40 +00005615 // Check for an altivec or OpenCL literal,
John Thompson8bb59a82010-06-30 22:55:51 +00005616 // i.e. all the elements are integer constants.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005617 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5618 if (PE->getNumExprs() == 0) {
5619 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5620 return ExprError();
5621 }
John Thompson8bb59a82010-06-30 22:55:51 +00005622 if (PE->getNumExprs() == 1) {
5623 if (!PE->getExpr(0)->getType()->isVectorType())
Anton Yartsevd06fea82011-03-27 09:32:40 +00005624 isVectorLiteral = true;
John Thompson8bb59a82010-06-30 22:55:51 +00005625 }
5626 else
Anton Yartsevd06fea82011-03-27 09:32:40 +00005627 isVectorLiteral = true;
John Thompson8bb59a82010-06-30 22:55:51 +00005628 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00005629
Anton Yartsevd06fea82011-03-27 09:32:40 +00005630 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
John Thompson8bb59a82010-06-30 22:55:51 +00005631 // then handle it as such.
Anton Yartsevd06fea82011-03-27 09:32:40 +00005632 if (isVectorLiteral) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005633 llvm::SmallVector<Expr *, 8> initExprs;
Anton Yartsevd06fea82011-03-27 09:32:40 +00005634 // '(...)' form of vector initialization in AltiVec: the number of
5635 // initializers must be one or must match the size of the vector.
5636 // If a single value is specified in the initializer then it will be
5637 // replicated to all the components of the vector
5638 if (Ty->getAs<VectorType>()->getVectorKind() ==
5639 VectorType::AltiVecVector) {
5640 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5641 // The number of initializers must be one or must match the size of the
5642 // vector. If a single value is specified in the initializer then it will
5643 // be replicated to all the components of the vector
5644 if (PE->getNumExprs() == 1) {
5645 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00005646 ExprResult Literal = Owned(PE->getExpr(0));
5647 Literal = ImpCastExprToType(Literal.take(), ElemTy,
5648 PrepareScalarCast(*this, Literal, ElemTy));
5649 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
Anton Yartsevd06fea82011-03-27 09:32:40 +00005650 }
5651 else if (PE->getNumExprs() < numElems) {
5652 Diag(PE->getExprLoc(),
5653 diag::err_incorrect_number_of_vector_initializers);
5654 return ExprError();
5655 }
5656 else
5657 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5658 initExprs.push_back(PE->getExpr(i));
5659 }
5660 else
5661 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5662 initExprs.push_back(PE->getExpr(i));
Nate Begeman2ef13e52009-08-10 23:49:36 +00005663
5664 // FIXME: This means that pretty-printing the final AST will produce curly
5665 // braces instead of the original commas.
Ted Kremenek709210f2010-04-13 23:39:13 +00005666 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5667 &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00005668 initExprs.size(), RParenLoc);
5669 E->setType(Ty);
John McCall9ae2f072010-08-23 23:25:46 +00005670 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005671 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005672 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00005673 // sequence of BinOp comma operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005674 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCall9ae2f072010-08-23 23:25:46 +00005675 if (Result.isInvalid()) return ExprError();
5676 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005677 }
5678}
5679
John McCall60d7b3a2010-08-24 06:29:42 +00005680ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00005681 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005682 MultiExprArg Val,
John McCallb3d87482010-08-24 05:47:05 +00005683 ParsedType TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005684 unsigned nexprs = Val.size();
5685 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005686 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5687 Expr *expr;
5688 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5689 expr = new (Context) ParenExpr(L, R, exprs[0]);
5690 else
5691 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005692 return Owned(expr);
5693}
5694
Chandler Carruth82214a82011-02-18 23:54:50 +00005695/// \brief Emit a specialized diagnostic when one expression is a null pointer
5696/// constant and the other is not a pointer.
5697bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5698 SourceLocation QuestionLoc) {
5699 Expr *NullExpr = LHS;
5700 Expr *NonPointerExpr = RHS;
5701 Expr::NullPointerConstantKind NullKind =
5702 NullExpr->isNullPointerConstant(Context,
5703 Expr::NPC_ValueDependentIsNotNull);
5704
5705 if (NullKind == Expr::NPCK_NotNull) {
5706 NullExpr = RHS;
5707 NonPointerExpr = LHS;
5708 NullKind =
5709 NullExpr->isNullPointerConstant(Context,
5710 Expr::NPC_ValueDependentIsNotNull);
5711 }
5712
5713 if (NullKind == Expr::NPCK_NotNull)
5714 return false;
5715
5716 if (NullKind == Expr::NPCK_ZeroInteger) {
5717 // In this case, check to make sure that we got here from a "NULL"
5718 // string in the source code.
5719 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00005720 SourceLocation loc = NullExpr->getExprLoc();
5721 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00005722 return false;
5723 }
5724
5725 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5726 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5727 << NonPointerExpr->getType() << DiagType
5728 << NonPointerExpr->getSourceRange();
5729 return true;
5730}
5731
Sebastian Redl28507842009-02-26 14:39:58 +00005732/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5733/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00005734/// C99 6.5.15
John Wiegley429bb272011-04-08 18:41:53 +00005735QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005736 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00005737 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00005738
John McCallfb8721c2011-04-10 19:13:55 +00005739 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00005740 if (!lhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00005741 LHS = move(lhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005742
John McCallfb8721c2011-04-10 19:13:55 +00005743 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00005744 if (!rhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00005745 RHS = move(rhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005746
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005747 // C++ is sufficiently different to merit its own checker.
5748 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00005749 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00005750
5751 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005752 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005753
John Wiegley429bb272011-04-08 18:41:53 +00005754 Cond = UsualUnaryConversions(Cond.take());
5755 if (Cond.isInvalid())
5756 return QualType();
5757 LHS = UsualUnaryConversions(LHS.take());
5758 if (LHS.isInvalid())
5759 return QualType();
5760 RHS = UsualUnaryConversions(RHS.take());
5761 if (RHS.isInvalid())
5762 return QualType();
5763
5764 QualType CondTy = Cond.get()->getType();
5765 QualType LHSTy = LHS.get()->getType();
5766 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005767
Reid Spencer5f016e22007-07-11 17:01:13 +00005768 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005769 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begeman6155d732010-09-20 22:41:17 +00005770 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5771 // Throw an error if its not either.
5772 if (getLangOptions().OpenCL) {
5773 if (!CondTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005774 Diag(Cond.get()->getLocStart(),
Nate Begeman6155d732010-09-20 22:41:17 +00005775 diag::err_typecheck_cond_expect_scalar_or_vector)
5776 << CondTy;
5777 return QualType();
5778 }
5779 }
5780 else {
John Wiegley429bb272011-04-08 18:41:53 +00005781 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00005782 << CondTy;
5783 return QualType();
5784 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005785 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005786
Chris Lattner70d67a92008-01-06 22:42:25 +00005787 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005788 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5789 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00005790
Nate Begeman6155d732010-09-20 22:41:17 +00005791 // OpenCL: If the condition is a vector, and both operands are scalar,
5792 // attempt to implicity convert them to the vector type to act like the
5793 // built in select.
5794 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5795 // Both operands should be of scalar type.
5796 if (!LHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005797 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00005798 << CondTy;
5799 return QualType();
5800 }
5801 if (!RHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005802 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00005803 << CondTy;
5804 return QualType();
5805 }
5806 // Implicity convert these scalars to the type of the condition.
John Wiegley429bb272011-04-08 18:41:53 +00005807 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5808 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begeman6155d732010-09-20 22:41:17 +00005809 }
5810
Chris Lattner70d67a92008-01-06 22:42:25 +00005811 // If both operands have arithmetic type, do the usual arithmetic conversions
5812 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005813 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5814 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00005815 if (LHS.isInvalid() || RHS.isInvalid())
5816 return QualType();
5817 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00005818 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005819
Chris Lattner70d67a92008-01-06 22:42:25 +00005820 // If both operands are the same structure or union type, the result is that
5821 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005822 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5823 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00005824 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005825 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005826 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005827 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005828 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005829 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005830
Chris Lattner70d67a92008-01-06 22:42:25 +00005831 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005832 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005833 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5834 if (!LHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00005835 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5836 << RHS.get()->getSourceRange();
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005837 if (!RHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00005838 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5839 << LHS.get()->getSourceRange();
5840 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
5841 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00005842 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00005843 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00005844 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5845 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005846 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley429bb272011-04-08 18:41:53 +00005847 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005848 // promote the null to a pointer.
John Wiegley429bb272011-04-08 18:41:53 +00005849 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005850 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005851 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005852 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley429bb272011-04-08 18:41:53 +00005853 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5854 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005855 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005856 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005857
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005858 // All objective-c pointer type analysis is done here.
5859 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5860 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005861 if (LHS.isInvalid() || RHS.isInvalid())
5862 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005863 if (!compositeType.isNull())
5864 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005865
5866
Steve Naroff7154a772009-07-01 14:36:47 +00005867 // Handle block pointer types.
5868 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5869 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5870 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5871 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00005872 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5873 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005874 return destType;
5875 }
5876 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00005877 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00005878 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005879 }
Steve Naroff7154a772009-07-01 14:36:47 +00005880 // We have 2 block pointer types.
5881 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5882 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005883 return LHSTy;
5884 }
Steve Naroff7154a772009-07-01 14:36:47 +00005885 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00005886 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5887 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005888
Steve Naroff7154a772009-07-01 14:36:47 +00005889 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5890 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00005891 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00005892 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005893 // In this situation, we assume void* type. No especially good
5894 // reason, but this is what gcc does, and we do have to pick
5895 // to get a consistent AST.
5896 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00005897 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5898 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00005899 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005900 }
Steve Naroff7154a772009-07-01 14:36:47 +00005901 // The block pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00005902 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5903 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00005904 return LHSTy;
5905 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005906
Steve Naroff7154a772009-07-01 14:36:47 +00005907 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5908 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5909 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00005910 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5911 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00005912
5913 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5914 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5915 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00005916 QualType destPointee
5917 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005918 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005919 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005920 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005921 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005922 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005923 return destType;
5924 }
5925 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00005926 QualType destPointee
5927 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005928 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005929 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005930 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005931 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005932 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005933 return destType;
5934 }
5935
5936 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5937 // Two identical pointer types are always compatible.
5938 return LHSTy;
5939 }
5940 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5941 rhptee.getUnqualifiedType())) {
5942 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00005943 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00005944 // In this situation, we assume void* type. No especially good
5945 // reason, but this is what gcc does, and we do have to pick
5946 // to get a consistent AST.
5947 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00005948 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5949 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005950 return incompatTy;
5951 }
5952 // The pointer types are compatible.
5953 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5954 // differently qualified versions of compatible types, the result type is
5955 // a pointer to an appropriately qualified version of the *composite*
5956 // type.
5957 // FIXME: Need to calculate the composite type.
5958 // FIXME: Need to add qualifiers
John Wiegley429bb272011-04-08 18:41:53 +00005959 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5960 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005961 return LHSTy;
5962 }
Mike Stump1eb44332009-09-09 15:08:12 +00005963
John McCall404cd162010-11-13 01:35:44 +00005964 // GCC compatibility: soften pointer/integer mismatch. Note that
5965 // null pointers have been filtered out by this point.
Steve Naroff7154a772009-07-01 14:36:47 +00005966 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5967 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley429bb272011-04-08 18:41:53 +00005968 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5969 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005970 return RHSTy;
5971 }
5972 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5973 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley429bb272011-04-08 18:41:53 +00005974 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5975 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005976 return LHSTy;
5977 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00005978
Chandler Carruth82214a82011-02-18 23:54:50 +00005979 // Emit a better diagnostic if one of the expressions is a null pointer
5980 // constant and the other is not a pointer type. In this case, the user most
5981 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00005982 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00005983 return QualType();
5984
Chris Lattner70d67a92008-01-06 22:42:25 +00005985 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005986 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00005987 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005988 return QualType();
5989}
5990
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005991/// FindCompositeObjCPointerType - Helper method to find composite type of
5992/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00005993QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005994 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00005995 QualType LHSTy = LHS.get()->getType();
5996 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005997
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005998 // Handle things like Class and struct objc_class*. Here we case the result
5999 // to the pseudo-builtin, because that will be implicitly cast back to the
6000 // redefinition type if an attempt is made to access its fields.
6001 if (LHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006002 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006003 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006004 return LHSTy;
6005 }
6006 if (RHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006007 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006008 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006009 return RHSTy;
6010 }
6011 // And the same for struct objc_object* / id
6012 if (LHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006013 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006014 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006015 return LHSTy;
6016 }
6017 if (RHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006018 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006019 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006020 return RHSTy;
6021 }
6022 // And the same for struct objc_selector* / SEL
6023 if (Context.isObjCSelType(LHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00006024 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006025 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006026 return LHSTy;
6027 }
6028 if (Context.isObjCSelType(RHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00006029 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006030 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006031 return RHSTy;
6032 }
6033 // Check constraints for Objective-C object pointers types.
6034 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006035
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006036 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6037 // Two identical object pointer types are always compatible.
6038 return LHSTy;
6039 }
6040 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
6041 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
6042 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006043
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006044 // If both operands are interfaces and either operand can be
6045 // assigned to the other, use that type as the composite
6046 // type. This allows
6047 // xxx ? (A*) a : (B*) b
6048 // where B is a subclass of A.
6049 //
6050 // Additionally, as for assignment, if either type is 'id'
6051 // allow silent coercion. Finally, if the types are
6052 // incompatible then make sure to use 'id' as the composite
6053 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006054
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006055 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6056 // It could return the composite type.
6057 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6058 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6059 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6060 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6061 } else if ((LHSTy->isObjCQualifiedIdType() ||
6062 RHSTy->isObjCQualifiedIdType()) &&
6063 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6064 // Need to handle "id<xx>" explicitly.
6065 // GCC allows qualified id and any Objective-C type to devolve to
6066 // id. Currently localizing to here until clear this should be
6067 // part of ObjCQualifiedIdTypesAreCompatible.
6068 compositeType = Context.getObjCIdType();
6069 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6070 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006071 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006072 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
6073 ;
6074 else {
6075 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6076 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00006077 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006078 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00006079 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6080 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006081 return incompatTy;
6082 }
6083 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00006084 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
6085 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006086 return compositeType;
6087 }
6088 // Check Objective-C object pointer types and 'void *'
6089 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6090 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6091 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6092 QualType destPointee
6093 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6094 QualType destType = Context.getPointerType(destPointee);
6095 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00006096 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006097 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00006098 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006099 return destType;
6100 }
6101 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6102 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6103 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6104 QualType destPointee
6105 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6106 QualType destType = Context.getPointerType(destPointee);
6107 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00006108 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006109 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00006110 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006111 return destType;
6112 }
6113 return QualType();
6114}
6115
Steve Narofff69936d2007-09-16 03:34:24 +00006116/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00006117/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00006118ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00006119 SourceLocation ColonLoc,
6120 Expr *CondExpr, Expr *LHSExpr,
6121 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00006122 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6123 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00006124 OpaqueValueExpr *opaqueValue = 0;
6125 Expr *commonExpr = 0;
6126 if (LHSExpr == 0) {
6127 commonExpr = CondExpr;
6128
6129 // We usually want to apply unary conversions *before* saving, except
6130 // in the special case of a C++ l-value conditional.
6131 if (!(getLangOptions().CPlusPlus
6132 && !commonExpr->isTypeDependent()
6133 && commonExpr->getValueKind() == RHSExpr->getValueKind()
6134 && commonExpr->isGLValue()
6135 && commonExpr->isOrdinaryOrBitFieldObject()
6136 && RHSExpr->isOrdinaryOrBitFieldObject()
6137 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00006138 ExprResult commonRes = UsualUnaryConversions(commonExpr);
6139 if (commonRes.isInvalid())
6140 return ExprError();
6141 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00006142 }
6143
6144 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6145 commonExpr->getType(),
6146 commonExpr->getValueKind(),
6147 commonExpr->getObjectKind());
6148 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00006149 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006150
John McCallf89e55a2010-11-18 06:31:45 +00006151 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00006152 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00006153 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
6154 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00006155 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00006156 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6157 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006158 return ExprError();
6159
John McCall56ca35d2011-02-17 10:25:35 +00006160 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00006161 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
6162 LHS.take(), ColonLoc,
6163 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00006164
6165 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00006166 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
6167 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00006168}
6169
John McCalle4be87e2011-01-31 23:13:11 +00006170// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00006171// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00006172// routine is it effectively iqnores the qualifiers on the top level pointee.
6173// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6174// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00006175static Sema::AssignConvertType
6176checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6177 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6178 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006179
Reid Spencer5f016e22007-07-11 17:01:13 +00006180 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00006181 const Type *lhptee, *rhptee;
6182 Qualifiers lhq, rhq;
6183 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
6184 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006185
John McCalle4be87e2011-01-31 23:13:11 +00006186 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006187
6188 // C99 6.5.16.1p1: This following citation is common to constraints
6189 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6190 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00006191 Qualifiers lq;
6192
6193 if (!lhq.compatiblyIncludes(rhq)) {
6194 // Treat address-space mismatches as fatal. TODO: address subspaces
6195 if (lhq.getAddressSpace() != rhq.getAddressSpace())
6196 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6197
John McCall22348732011-03-26 02:56:45 +00006198 // It's okay to add or remove GC qualifiers when converting to
6199 // and from void*.
6200 else if (lhq.withoutObjCGCAttr().compatiblyIncludes(rhq.withoutObjCGCAttr())
6201 && (lhptee->isVoidType() || rhptee->isVoidType()))
6202 ; // keep old
6203
John McCall86c05f32011-02-01 00:10:29 +00006204 // For GCC compatibility, other qualifier mismatches are treated
6205 // as still compatible in C.
6206 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6207 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006208
Mike Stumpeed9cac2009-02-19 03:04:26 +00006209 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6210 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00006211 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006212 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00006213 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00006214 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006215
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006216 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00006217 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00006218 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006219 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006220
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006221 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00006222 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00006223 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006224
6225 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00006226 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00006227 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006228 }
John McCall86c05f32011-02-01 00:10:29 +00006229
Mike Stumpeed9cac2009-02-19 03:04:26 +00006230 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00006231 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00006232 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6233 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006234 // Check if the pointee types are compatible ignoring the sign.
6235 // We explicitly check for char so that we catch "char" vs
6236 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00006237 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00006238 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00006239 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00006240 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006241
Chris Lattner6a2b9262009-10-17 20:33:28 +00006242 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00006243 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00006244 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00006245 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00006246
John McCall86c05f32011-02-01 00:10:29 +00006247 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006248 // Types are compatible ignoring the sign. Qualifier incompatibility
6249 // takes priority over sign incompatibility because the sign
6250 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00006251 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006252 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00006253
John McCalle4be87e2011-01-31 23:13:11 +00006254 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006255 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006256
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006257 // If we are a multi-level pointer, it's possible that our issue is simply
6258 // one of qualification - e.g. char ** -> const char ** is not allowed. If
6259 // the eventual target type is the same and the pointers have the same
6260 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00006261 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006262 do {
John McCall86c05f32011-02-01 00:10:29 +00006263 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6264 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00006265 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006266
John McCall86c05f32011-02-01 00:10:29 +00006267 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00006268 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006269 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006270
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006271 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00006272 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006273 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00006274 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006275}
6276
John McCalle4be87e2011-01-31 23:13:11 +00006277/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00006278/// block pointer types are compatible or whether a block and normal pointer
6279/// are compatible. It is more restrict than comparing two function pointer
6280// types.
John McCalle4be87e2011-01-31 23:13:11 +00006281static Sema::AssignConvertType
6282checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
6283 QualType rhsType) {
6284 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6285 assert(rhsType.isCanonical() && "RHS not canonicalized!");
6286
Steve Naroff1c7d0672008-09-04 15:10:53 +00006287 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006288
Steve Naroff1c7d0672008-09-04 15:10:53 +00006289 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCalle4be87e2011-01-31 23:13:11 +00006290 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
6291 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006292
John McCalle4be87e2011-01-31 23:13:11 +00006293 // In C++, the types have to match exactly.
6294 if (S.getLangOptions().CPlusPlus)
6295 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006296
John McCalle4be87e2011-01-31 23:13:11 +00006297 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006298
Steve Naroff1c7d0672008-09-04 15:10:53 +00006299 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00006300 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6301 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006302
John McCalle4be87e2011-01-31 23:13:11 +00006303 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
6304 return Sema::IncompatibleBlockPointer;
6305
Steve Naroff1c7d0672008-09-04 15:10:53 +00006306 return ConvTy;
6307}
6308
John McCalle4be87e2011-01-31 23:13:11 +00006309/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006310/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00006311static Sema::AssignConvertType
6312checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6313 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
6314 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
6315
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006316 if (lhsType->isObjCBuiltinType()) {
6317 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00006318 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
6319 !rhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00006320 return Sema::IncompatiblePointer;
6321 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006322 }
6323 if (rhsType->isObjCBuiltinType()) {
6324 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00006325 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
6326 !lhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00006327 return Sema::IncompatiblePointer;
6328 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006329 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006330 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006331 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006332 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006333 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006334
John McCalle4be87e2011-01-31 23:13:11 +00006335 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
6336 return Sema::CompatiblePointerDiscardsQualifiers;
6337
6338 if (S.Context.typesAreCompatible(lhsType, rhsType))
6339 return Sema::Compatible;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006340 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00006341 return Sema::IncompatibleObjCQualifiedId;
6342 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006343}
6344
John McCall1c23e912010-11-16 02:32:08 +00006345Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00006346Sema::CheckAssignmentConstraints(SourceLocation Loc,
6347 QualType lhsType, QualType rhsType) {
John McCall1c23e912010-11-16 02:32:08 +00006348 // Fake up an opaque expression. We don't actually care about what
6349 // cast operations are required, so if CheckAssignmentConstraints
6350 // adds casts to this they'll be wasted, but fortunately that doesn't
6351 // usually happen on valid code.
Douglas Gregorb608b982011-01-28 02:26:04 +00006352 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00006353 ExprResult rhsPtr = &rhs;
John McCall1c23e912010-11-16 02:32:08 +00006354 CastKind K = CK_Invalid;
6355
6356 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
6357}
6358
Mike Stumpeed9cac2009-02-19 03:04:26 +00006359/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6360/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00006361/// pointers. Here are some objectionable examples that GCC considers warnings:
6362///
6363/// int a, *pint;
6364/// short *pshort;
6365/// struct foo *pfoo;
6366///
6367/// pint = pshort; // warning: assignment from incompatible pointer type
6368/// a = pint; // warning: assignment makes integer from pointer without a cast
6369/// pint = a; // warning: assignment makes pointer from integer without a cast
6370/// pint = pfoo; // warning: assignment from incompatible pointer type
6371///
6372/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00006373/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00006374///
John McCalldaa8e4e2010-11-15 09:13:47 +00006375/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00006376Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00006377Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCalldaa8e4e2010-11-15 09:13:47 +00006378 CastKind &Kind) {
John Wiegley429bb272011-04-08 18:41:53 +00006379 QualType rhsType = rhs.get()->getType();
John McCall1c23e912010-11-16 02:32:08 +00006380
Chris Lattnerfc144e22008-01-04 23:18:45 +00006381 // Get canonical types. We're not formatting these types, just comparing
6382 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00006383 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
6384 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006385
John McCallb6cfa242011-01-31 22:28:28 +00006386 // Common case: no conversion required.
John McCalldaa8e4e2010-11-15 09:13:47 +00006387 if (lhsType == rhsType) {
6388 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00006389 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00006390 }
6391
Douglas Gregor9d293df2008-10-28 00:22:11 +00006392 // If the left-hand side is a reference type, then we are in a
6393 // (rare!) case where we've allowed the use of references in C,
6394 // e.g., as a parameter type in a built-in function. In this case,
6395 // just make sure that the type referenced is compatible with the
6396 // right-hand side type. The caller is responsible for adjusting
6397 // lhsType so that the resulting expression does not have reference
6398 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00006399 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006400 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
6401 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00006402 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006403 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00006404 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00006405 }
John McCallb6cfa242011-01-31 22:28:28 +00006406
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006407 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6408 // to the same ExtVector type.
6409 if (lhsType->isExtVectorType()) {
6410 if (rhsType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00006411 return Incompatible;
6412 if (rhsType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00006413 // CK_VectorSplat does T -> vector T, so first cast to the
6414 // element type.
6415 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
6416 if (elType != rhsType) {
6417 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley429bb272011-04-08 18:41:53 +00006418 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00006419 }
6420 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006421 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006422 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006423 }
Mike Stump1eb44332009-09-09 15:08:12 +00006424
John McCallb6cfa242011-01-31 22:28:28 +00006425 // Conversions to or from vector type.
Nate Begemanbe2341d2008-07-14 18:02:46 +00006426 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00006427 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00006428 // Allow assignments of an AltiVec vector type to an equivalent GCC
6429 // vector type and vice versa
6430 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6431 Kind = CK_BitCast;
6432 return Compatible;
6433 }
6434
Douglas Gregor255210e2010-08-06 10:14:59 +00006435 // If we are allowing lax vector conversions, and LHS and RHS are both
6436 // vectors, the total size only needs to be the same. This is a bitcast;
6437 // no bits are changed but the result type is different.
6438 if (getLangOptions().LaxVectorConversions &&
John McCalldaa8e4e2010-11-15 09:13:47 +00006439 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00006440 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006441 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00006442 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00006443 }
6444 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006445 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006446
John McCallb6cfa242011-01-31 22:28:28 +00006447 // Arithmetic conversions.
Douglas Gregor88623ad2010-05-23 21:53:47 +00006448 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00006449 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall1c23e912010-11-16 02:32:08 +00006450 Kind = PrepareScalarCast(*this, rhs, lhsType);
Reid Spencer5f016e22007-07-11 17:01:13 +00006451 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006452 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006453
John McCallb6cfa242011-01-31 22:28:28 +00006454 // Conversions to normal pointers.
6455 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6456 // U* -> T*
John McCalldaa8e4e2010-11-15 09:13:47 +00006457 if (isa<PointerType>(rhsType)) {
6458 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00006459 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006460 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006461
John McCallb6cfa242011-01-31 22:28:28 +00006462 // int -> T*
6463 if (rhsType->isIntegerType()) {
6464 Kind = CK_IntegralToPointer; // FIXME: null?
6465 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006466 }
John McCallb6cfa242011-01-31 22:28:28 +00006467
6468 // C pointers are not compatible with ObjC object pointers,
6469 // with two exceptions:
6470 if (isa<ObjCObjectPointerType>(rhsType)) {
6471 // - conversions to void*
6472 if (lhsPointer->getPointeeType()->isVoidType()) {
6473 Kind = CK_AnyPointerToObjCPointerCast;
6474 return Compatible;
6475 }
6476
6477 // - conversions from 'Class' to the redefinition type
6478 if (rhsType->isObjCClassType() &&
6479 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006480 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006481 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006482 }
Steve Naroffb4406862008-09-29 18:10:17 +00006483
John McCallb6cfa242011-01-31 22:28:28 +00006484 Kind = CK_BitCast;
6485 return IncompatiblePointer;
6486 }
6487
6488 // U^ -> void*
6489 if (rhsType->getAs<BlockPointerType>()) {
6490 if (lhsPointer->getPointeeType()->isVoidType()) {
6491 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006492 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006493 }
Steve Naroffb4406862008-09-29 18:10:17 +00006494 }
John McCallb6cfa242011-01-31 22:28:28 +00006495
Steve Naroff1c7d0672008-09-04 15:10:53 +00006496 return Incompatible;
6497 }
6498
John McCallb6cfa242011-01-31 22:28:28 +00006499 // Conversions to block pointers.
Steve Naroff1c7d0672008-09-04 15:10:53 +00006500 if (isa<BlockPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006501 // U^ -> T^
6502 if (rhsType->isBlockPointerType()) {
6503 Kind = CK_AnyPointerToBlockPointerCast;
John McCalle4be87e2011-01-31 23:13:11 +00006504 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00006505 }
6506
6507 // int or null -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00006508 if (rhsType->isIntegerType()) {
6509 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00006510 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006511 }
6512
John McCallb6cfa242011-01-31 22:28:28 +00006513 // id -> T^
6514 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6515 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006516 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006517 }
Steve Naroffb4406862008-09-29 18:10:17 +00006518
John McCallb6cfa242011-01-31 22:28:28 +00006519 // void* -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00006520 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00006521 if (RHSPT->getPointeeType()->isVoidType()) {
6522 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006523 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006524 }
John McCalldaa8e4e2010-11-15 09:13:47 +00006525
Chris Lattnerfc144e22008-01-04 23:18:45 +00006526 return Incompatible;
6527 }
6528
John McCallb6cfa242011-01-31 22:28:28 +00006529 // Conversions to Objective-C pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00006530 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006531 // A* -> B*
6532 if (rhsType->isObjCObjectPointerType()) {
6533 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00006534 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00006535 }
6536
6537 // int or null -> A*
John McCalldaa8e4e2010-11-15 09:13:47 +00006538 if (rhsType->isIntegerType()) {
6539 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00006540 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006541 }
6542
John McCallb6cfa242011-01-31 22:28:28 +00006543 // In general, C pointers are not compatible with ObjC object pointers,
6544 // with two exceptions:
Steve Naroff14108da2009-07-10 23:34:53 +00006545 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006546 // - conversions from 'void*'
6547 if (rhsType->isVoidPointerType()) {
6548 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006549 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006550 }
6551
6552 // - conversions to 'Class' from its redefinition type
6553 if (lhsType->isObjCClassType() &&
6554 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6555 Kind = CK_BitCast;
6556 return Compatible;
6557 }
6558
6559 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006560 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006561 }
John McCallb6cfa242011-01-31 22:28:28 +00006562
6563 // T^ -> A*
6564 if (rhsType->isBlockPointerType()) {
6565 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00006566 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006567 }
6568
Steve Naroff14108da2009-07-10 23:34:53 +00006569 return Incompatible;
6570 }
John McCallb6cfa242011-01-31 22:28:28 +00006571
6572 // Conversions from pointers that are not covered by the above.
Chris Lattner78eca282008-04-07 06:49:41 +00006573 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006574 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006575 if (lhsType == Context.BoolTy) {
6576 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006577 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006578 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006579
John McCallb6cfa242011-01-31 22:28:28 +00006580 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006581 if (lhsType->isIntegerType()) {
6582 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006583 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006584 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006585
Chris Lattnerfc144e22008-01-04 23:18:45 +00006586 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00006587 }
John McCallb6cfa242011-01-31 22:28:28 +00006588
6589 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff14108da2009-07-10 23:34:53 +00006590 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006591 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006592 if (lhsType == Context.BoolTy) {
6593 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00006594 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006595 }
Steve Naroff14108da2009-07-10 23:34:53 +00006596
John McCallb6cfa242011-01-31 22:28:28 +00006597 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006598 if (lhsType->isIntegerType()) {
6599 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00006600 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006601 }
6602
Steve Naroff14108da2009-07-10 23:34:53 +00006603 return Incompatible;
6604 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006605
John McCallb6cfa242011-01-31 22:28:28 +00006606 // struct A -> struct B
Chris Lattnerfc144e22008-01-04 23:18:45 +00006607 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006608 if (Context.typesAreCompatible(lhsType, rhsType)) {
6609 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00006610 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006611 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006612 }
John McCallb6cfa242011-01-31 22:28:28 +00006613
Reid Spencer5f016e22007-07-11 17:01:13 +00006614 return Incompatible;
6615}
6616
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006617/// \brief Constructs a transparent union from an expression that is
6618/// used to initialize the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00006619static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006620 QualType UnionType, FieldDecl *Field) {
6621 // Build an initializer list that designates the appropriate member
6622 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00006623 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00006624 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00006625 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006626 SourceLocation());
6627 Initializer->setType(UnionType);
6628 Initializer->setInitializedFieldInUnion(Field);
6629
6630 // Build a compound literal constructing a value of the transparent
6631 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00006632 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00006633 EResult = S.Owned(
6634 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6635 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006636}
6637
6638Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00006639Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
6640 QualType FromType = rExpr.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006641
Mike Stump1eb44332009-09-09 15:08:12 +00006642 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006643 // transparent_union GCC extension.
6644 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006645 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006646 return Incompatible;
6647
6648 // The field to initialize within the transparent union.
6649 RecordDecl *UD = UT->getDecl();
6650 FieldDecl *InitField = 0;
6651 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006652 for (RecordDecl::field_iterator it = UD->field_begin(),
6653 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006654 it != itend; ++it) {
6655 if (it->getType()->isPointerType()) {
6656 // If the transparent union contains a pointer type, we allow:
6657 // 1) void pointer
6658 // 2) null pointer constant
6659 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00006660 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006661 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006662 InitField = *it;
6663 break;
6664 }
Mike Stump1eb44332009-09-09 15:08:12 +00006665
John Wiegley429bb272011-04-08 18:41:53 +00006666 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006667 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006668 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006669 InitField = *it;
6670 break;
6671 }
6672 }
6673
John McCalldaa8e4e2010-11-15 09:13:47 +00006674 CastKind Kind = CK_Invalid;
John Wiegley429bb272011-04-08 18:41:53 +00006675 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006676 == Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +00006677 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006678 InitField = *it;
6679 break;
6680 }
6681 }
6682
6683 if (!InitField)
6684 return Incompatible;
6685
John Wiegley429bb272011-04-08 18:41:53 +00006686 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006687 return Compatible;
6688}
6689
Chris Lattner5cf216b2008-01-04 18:04:52 +00006690Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00006691Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00006692 if (getLangOptions().CPlusPlus) {
6693 if (!lhsType->isRecordType()) {
6694 // C++ 5.17p3: If the left operand is not of class type, the
6695 // expression is implicitly converted (C++ 4) to the
6696 // cv-unqualified type of the left operand.
John Wiegley429bb272011-04-08 18:41:53 +00006697 ExprResult Res = PerformImplicitConversion(rExpr.get(),
6698 lhsType.getUnqualifiedType(),
6699 AA_Assigning);
6700 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00006701 return Incompatible;
John Wiegley429bb272011-04-08 18:41:53 +00006702 rExpr = move(Res);
Chris Lattner2c4463f2009-04-12 09:02:39 +00006703 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00006704 }
6705
6706 // FIXME: Currently, we fall through and treat C++ classes like C
6707 // structures.
John McCallf6a16482010-12-04 03:47:34 +00006708 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00006709
Steve Naroff529a4ad2007-11-27 17:58:44 +00006710 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6711 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00006712 if ((lhsType->isPointerType() ||
6713 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00006714 lhsType->isBlockPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00006715 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006716 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006717 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00006718 return Compatible;
6719 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006720
Chris Lattner943140e2007-10-16 02:55:40 +00006721 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00006722 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00006723 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00006724 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00006725 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00006726 // Suppress this for references: C++ 8.5.3p5.
John Wiegley429bb272011-04-08 18:41:53 +00006727 if (!lhsType->isReferenceType()) {
6728 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
6729 if (rExpr.isInvalid())
6730 return Incompatible;
6731 }
Steve Narofff1120de2007-08-24 22:33:52 +00006732
John McCalldaa8e4e2010-11-15 09:13:47 +00006733 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006734 Sema::AssignConvertType result =
John McCall1c23e912010-11-16 02:32:08 +00006735 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006736
Steve Narofff1120de2007-08-24 22:33:52 +00006737 // C99 6.5.16.1p2: The value of the right operand is converted to the
6738 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00006739 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6740 // so that we can use references in built-in functions even in C.
6741 // The getNonReferenceType() call makes sure that the resulting expression
6742 // does not have reference type.
John Wiegley429bb272011-04-08 18:41:53 +00006743 if (result != Incompatible && rExpr.get()->getType() != lhsType)
6744 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00006745 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00006746}
6747
John Wiegley429bb272011-04-08 18:41:53 +00006748QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006749 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley429bb272011-04-08 18:41:53 +00006750 << lex.get()->getType() << rex.get()->getType()
6751 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00006752 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006753}
6754
John Wiegley429bb272011-04-08 18:41:53 +00006755QualType Sema::CheckVectorOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00006756 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006757 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00006758 QualType lhsType =
John Wiegley429bb272011-04-08 18:41:53 +00006759 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattnerb77792e2008-07-26 22:17:49 +00006760 QualType rhsType =
John Wiegley429bb272011-04-08 18:41:53 +00006761 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006762
Nate Begemanbe2341d2008-07-14 18:02:46 +00006763 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006764 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00006765 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00006766
Nate Begemanbe2341d2008-07-14 18:02:46 +00006767 // Handle the case of a vector & extvector type of the same size and element
6768 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006769 if (getLangOptions().LaxVectorConversions) {
John McCall183700f2009-09-21 23:43:11 +00006770 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth629f9e42010-08-30 07:36:24 +00006771 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00006772 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006773 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregor26bcf672010-05-19 03:21:00 +00006774 if (lhsType->isExtVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006775 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006776 return lhsType;
6777 }
6778
John Wiegley429bb272011-04-08 18:41:53 +00006779 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006780 return rhsType;
Eric Christophere84f9eb2010-08-26 00:42:16 +00006781 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6782 // If we are allowing lax vector conversions, and LHS and RHS are both
6783 // vectors, the total size only needs to be the same. This is a
6784 // bitcast; no bits are changed but the result type is different.
John Wiegley429bb272011-04-08 18:41:53 +00006785 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Eric Christophere84f9eb2010-08-26 00:42:16 +00006786 return lhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006787 }
Eric Christophere84f9eb2010-08-26 00:42:16 +00006788 }
Chandler Carruth629f9e42010-08-30 07:36:24 +00006789 }
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006790 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006791
Douglas Gregor255210e2010-08-06 10:14:59 +00006792 // Handle the case of equivalent AltiVec and GCC vector types
6793 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6794 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John Wiegley429bb272011-04-08 18:41:53 +00006795 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor255210e2010-08-06 10:14:59 +00006796 return rhsType;
6797 }
6798
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006799 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6800 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6801 bool swapped = false;
6802 if (rhsType->isExtVectorType()) {
6803 swapped = true;
6804 std::swap(rex, lex);
6805 std::swap(rhsType, lhsType);
6806 }
Mike Stump1eb44332009-09-09 15:08:12 +00006807
Nate Begemandde25982009-06-28 19:12:57 +00006808 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00006809 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006810 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00006811 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006812 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6813 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00006814 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006815 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00006816 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006817 if (swapped) std::swap(rex, lex);
6818 return lhsType;
6819 }
6820 }
6821 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6822 rhsType->isRealFloatingType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006823 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6824 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00006825 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006826 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00006827 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006828 if (swapped) std::swap(rex, lex);
6829 return lhsType;
6830 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006831 }
6832 }
Mike Stump1eb44332009-09-09 15:08:12 +00006833
Nate Begemandde25982009-06-28 19:12:57 +00006834 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006835 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley429bb272011-04-08 18:41:53 +00006836 << lex.get()->getType() << rex.get()->getType()
6837 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006838 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006839}
6840
Chris Lattner7ef655a2010-01-12 21:23:57 +00006841QualType Sema::CheckMultiplyDivideOperands(
John Wiegley429bb272011-04-08 18:41:53 +00006842 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
6843 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006844 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006845
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006846 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00006847 if (lex.isInvalid() || rex.isInvalid())
6848 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006849
John Wiegley429bb272011-04-08 18:41:53 +00006850 if (!lex.get()->getType()->isArithmeticType() ||
6851 !rex.get()->getType()->isArithmeticType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00006852 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006853
Chris Lattner7ef655a2010-01-12 21:23:57 +00006854 // Check for division by zero.
6855 if (isDiv &&
John Wiegley429bb272011-04-08 18:41:53 +00006856 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6857 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
6858 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006859
Chris Lattner7ef655a2010-01-12 21:23:57 +00006860 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006861}
6862
Chris Lattner7ef655a2010-01-12 21:23:57 +00006863QualType Sema::CheckRemainderOperands(
John Wiegley429bb272011-04-08 18:41:53 +00006864 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
6865 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6866 if (lex.get()->getType()->hasIntegerRepresentation() &&
6867 rex.get()->getType()->hasIntegerRepresentation())
Daniel Dunbar523aa602009-01-05 22:55:36 +00006868 return CheckVectorOperands(Loc, lex, rex);
6869 return InvalidOperands(Loc, lex, rex);
6870 }
Steve Naroff90045e82007-07-13 23:32:42 +00006871
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006872 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00006873 if (lex.isInvalid() || rex.isInvalid())
6874 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006875
John Wiegley429bb272011-04-08 18:41:53 +00006876 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00006877 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006878
Chris Lattner7ef655a2010-01-12 21:23:57 +00006879 // Check for remainder by zero.
John Wiegley429bb272011-04-08 18:41:53 +00006880 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6881 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
6882 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006883
Chris Lattner7ef655a2010-01-12 21:23:57 +00006884 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006885}
6886
Chris Lattner7ef655a2010-01-12 21:23:57 +00006887QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00006888 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
6889 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006890 QualType compType = CheckVectorOperands(Loc, lex, rex);
6891 if (CompLHSTy) *CompLHSTy = compType;
6892 return compType;
6893 }
Steve Naroff49b45262007-07-13 16:58:59 +00006894
Eli Friedmanab3a8522009-03-28 01:22:36 +00006895 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00006896 if (lex.isInvalid() || rex.isInvalid())
6897 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006898
Reid Spencer5f016e22007-07-11 17:01:13 +00006899 // handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00006900 if (lex.get()->getType()->isArithmeticType() &&
6901 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006902 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006903 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006904 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006905
Eli Friedmand72d16e2008-05-18 18:08:51 +00006906 // Put any potential pointer into PExp
John Wiegley429bb272011-04-08 18:41:53 +00006907 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006908 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00006909 std::swap(PExp, IExp);
6910
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006911 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006912
Eli Friedmand72d16e2008-05-18 18:08:51 +00006913 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00006914 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00006915
Chris Lattnerb5f15622009-04-24 23:50:08 +00006916 // Check for arithmetic on pointers to incomplete types.
6917 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006918 if (getLangOptions().CPlusPlus) {
6919 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00006920 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006921 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006922 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006923
6924 // GNU extension: arithmetic on pointer to void
6925 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00006926 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00006927 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006928 if (getLangOptions().CPlusPlus) {
6929 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00006930 << lex.get()->getType() << lex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00006931 return QualType();
6932 }
6933
6934 // GNU extension: arithmetic on pointer to function
6935 Diag(Loc, diag::ext_gnu_ptr_func_arith)
John Wiegley429bb272011-04-08 18:41:53 +00006936 << lex.get()->getType() << lex.get()->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00006937 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00006938 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00006939 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00006940 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00006941 PExp->getType()->isObjCObjectPointerType()) &&
6942 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00006943 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6944 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006945 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00006946 return QualType();
6947 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00006948 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006949 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006950 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6951 << PointeeTy << PExp->getSourceRange();
6952 return QualType();
6953 }
Mike Stump1eb44332009-09-09 15:08:12 +00006954
Eli Friedmanab3a8522009-03-28 01:22:36 +00006955 if (CompLHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00006956 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman04e83572009-08-20 04:21:42 +00006957 if (LHSTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +00006958 LHSTy = lex.get()->getType();
Eli Friedman04e83572009-08-20 04:21:42 +00006959 if (LHSTy->isPromotableIntegerType())
6960 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00006961 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00006962 *CompLHSTy = LHSTy;
6963 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00006964 return PExp->getType();
6965 }
6966 }
6967
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006968 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006969}
6970
Chris Lattnereca7be62008-04-07 05:30:13 +00006971// C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00006972QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006973 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00006974 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006975 QualType compType = CheckVectorOperands(Loc, lex, rex);
6976 if (CompLHSTy) *CompLHSTy = compType;
6977 return compType;
6978 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006979
Eli Friedmanab3a8522009-03-28 01:22:36 +00006980 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00006981 if (lex.isInvalid() || rex.isInvalid())
6982 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006983
Chris Lattner6e4ab612007-12-09 21:53:25 +00006984 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006985
Chris Lattner6e4ab612007-12-09 21:53:25 +00006986 // Handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00006987 if (lex.get()->getType()->isArithmeticType() &&
6988 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006989 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006990 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006991 }
Mike Stump1eb44332009-09-09 15:08:12 +00006992
Chris Lattner6e4ab612007-12-09 21:53:25 +00006993 // Either ptr - int or ptr - ptr.
John Wiegley429bb272011-04-08 18:41:53 +00006994 if (lex.get()->getType()->isAnyPointerType()) {
6995 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006996
Douglas Gregore7450f52009-03-24 19:52:54 +00006997 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00006998
Douglas Gregore7450f52009-03-24 19:52:54 +00006999 bool ComplainAboutVoid = false;
7000 Expr *ComplainAboutFunc = 0;
7001 if (lpointee->isVoidType()) {
7002 if (getLangOptions().CPlusPlus) {
7003 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00007004 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007005 return QualType();
7006 }
7007
7008 // GNU C extension: arithmetic on pointer to void
7009 ComplainAboutVoid = true;
7010 } else if (lpointee->isFunctionType()) {
7011 if (getLangOptions().CPlusPlus) {
7012 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00007013 << lex.get()->getType() << lex.get()->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007014 return QualType();
7015 }
Douglas Gregore7450f52009-03-24 19:52:54 +00007016
7017 // GNU C extension: arithmetic on pointer to function
John Wiegley429bb272011-04-08 18:41:53 +00007018 ComplainAboutFunc = lex.get();
Douglas Gregore7450f52009-03-24 19:52:54 +00007019 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00007020 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00007021 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley429bb272011-04-08 18:41:53 +00007022 << lex.get()->getSourceRange()
7023 << lex.get()->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00007024 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007025
Chris Lattnerb5f15622009-04-24 23:50:08 +00007026 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00007027 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00007028 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley429bb272011-04-08 18:41:53 +00007029 << lpointee << lex.get()->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00007030 return QualType();
7031 }
Mike Stump1eb44332009-09-09 15:08:12 +00007032
Chris Lattner6e4ab612007-12-09 21:53:25 +00007033 // The result type of a pointer-int computation is the pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00007034 if (rex.get()->getType()->isIntegerType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00007035 if (ComplainAboutVoid)
7036 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00007037 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007038 if (ComplainAboutFunc)
7039 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00007040 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00007041 << ComplainAboutFunc->getSourceRange();
7042
John Wiegley429bb272011-04-08 18:41:53 +00007043 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
7044 return lex.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00007045 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007046
Chris Lattner6e4ab612007-12-09 21:53:25 +00007047 // Handle pointer-pointer subtractions.
John Wiegley429bb272011-04-08 18:41:53 +00007048 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00007049 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007050
Douglas Gregore7450f52009-03-24 19:52:54 +00007051 // RHS must be a completely-type object type.
7052 // Handle the GNU void* extension.
7053 if (rpointee->isVoidType()) {
7054 if (getLangOptions().CPlusPlus) {
7055 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00007056 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007057 return QualType();
7058 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007059
Douglas Gregore7450f52009-03-24 19:52:54 +00007060 ComplainAboutVoid = true;
7061 } else if (rpointee->isFunctionType()) {
7062 if (getLangOptions().CPlusPlus) {
7063 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00007064 << rex.get()->getType() << rex.get()->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007065 return QualType();
7066 }
Douglas Gregore7450f52009-03-24 19:52:54 +00007067
7068 // GNU extension: arithmetic on pointer to function
7069 if (!ComplainAboutFunc)
John Wiegley429bb272011-04-08 18:41:53 +00007070 ComplainAboutFunc = rex.get();
Douglas Gregore7450f52009-03-24 19:52:54 +00007071 } else if (!rpointee->isDependentType() &&
7072 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00007073 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley429bb272011-04-08 18:41:53 +00007074 << rex.get()->getSourceRange()
7075 << rex.get()->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00007076 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007077
Eli Friedman88d936b2009-05-16 13:54:38 +00007078 if (getLangOptions().CPlusPlus) {
7079 // Pointee types must be the same: C++ [expr.add]
7080 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7081 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley429bb272011-04-08 18:41:53 +00007082 << lex.get()->getType() << rex.get()->getType()
7083 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman88d936b2009-05-16 13:54:38 +00007084 return QualType();
7085 }
7086 } else {
7087 // Pointee types must be compatible C99 6.5.6p3
7088 if (!Context.typesAreCompatible(
7089 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7090 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7091 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley429bb272011-04-08 18:41:53 +00007092 << lex.get()->getType() << rex.get()->getType()
7093 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman88d936b2009-05-16 13:54:38 +00007094 return QualType();
7095 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00007096 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007097
Douglas Gregore7450f52009-03-24 19:52:54 +00007098 if (ComplainAboutVoid)
7099 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00007100 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007101 if (ComplainAboutFunc)
7102 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00007103 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00007104 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00007105
John Wiegley429bb272011-04-08 18:41:53 +00007106 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007107 return Context.getPointerDiffType();
7108 }
7109 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007110
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007111 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007112}
7113
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007114static bool isScopedEnumerationType(QualType T) {
7115 if (const EnumType *ET = dyn_cast<EnumType>(T))
7116 return ET->getDecl()->isScoped();
7117 return false;
7118}
7119
John Wiegley429bb272011-04-08 18:41:53 +00007120static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth21206d52011-02-23 23:34:11 +00007121 SourceLocation Loc, unsigned Opc,
7122 QualType LHSTy) {
7123 llvm::APSInt Right;
7124 // Check right/shifter operand
John Wiegley429bb272011-04-08 18:41:53 +00007125 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00007126 return;
7127
7128 if (Right.isNegative()) {
John Wiegley429bb272011-04-08 18:41:53 +00007129 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00007130 S.PDiag(diag::warn_shift_negative)
John Wiegley429bb272011-04-08 18:41:53 +00007131 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00007132 return;
7133 }
7134 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley429bb272011-04-08 18:41:53 +00007135 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00007136 if (Right.uge(LeftBits)) {
John Wiegley429bb272011-04-08 18:41:53 +00007137 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00007138 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley429bb272011-04-08 18:41:53 +00007139 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00007140 return;
7141 }
7142 if (Opc != BO_Shl)
7143 return;
7144
7145 // When left shifting an ICE which is signed, we can check for overflow which
7146 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7147 // integers have defined behavior modulo one more than the maximum value
7148 // representable in the result type, so never warn for those.
7149 llvm::APSInt Left;
John Wiegley429bb272011-04-08 18:41:53 +00007150 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth21206d52011-02-23 23:34:11 +00007151 LHSTy->hasUnsignedIntegerRepresentation())
7152 return;
7153 llvm::APInt ResultBits =
7154 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7155 if (LeftBits.uge(ResultBits))
7156 return;
7157 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7158 Result = Result.shl(Right);
7159
7160 // If we are only missing a sign bit, this is less likely to result in actual
7161 // bugs -- if the result is cast back to an unsigned type, it will have the
7162 // expected value. Thus we place this behind a different warning that can be
7163 // turned off separately if needed.
7164 if (LeftBits == ResultBits - 1) {
7165 S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
7166 << Result.toString(10) << LHSTy
John Wiegley429bb272011-04-08 18:41:53 +00007167 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00007168 return;
7169 }
7170
7171 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7172 << Result.toString(10) << Result.getMinSignedBits() << LHSTy
John Wiegley429bb272011-04-08 18:41:53 +00007173 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00007174}
7175
Chris Lattnereca7be62008-04-07 05:30:13 +00007176// C99 6.5.7
John Wiegley429bb272011-04-08 18:41:53 +00007177QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth21206d52011-02-23 23:34:11 +00007178 unsigned Opc, bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00007179 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley429bb272011-04-08 18:41:53 +00007180 if (!lex.get()->getType()->hasIntegerRepresentation() ||
7181 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007182 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007183
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007184 // C++0x: Don't allow scoped enums. FIXME: Use something better than
7185 // hasIntegerRepresentation() above instead of this.
John Wiegley429bb272011-04-08 18:41:53 +00007186 if (isScopedEnumerationType(lex.get()->getType()) ||
7187 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007188 return InvalidOperands(Loc, lex, rex);
7189 }
7190
Nate Begeman2207d792009-10-25 02:26:48 +00007191 // Vector shifts promote their scalar inputs to vector type.
John Wiegley429bb272011-04-08 18:41:53 +00007192 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Nate Begeman2207d792009-10-25 02:26:48 +00007193 return CheckVectorOperands(Loc, lex, rex);
7194
Chris Lattnerca5eede2007-12-12 05:47:28 +00007195 // Shifts don't perform usual arithmetic conversions, they just do integer
7196 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00007197
John McCall1bc80af2010-12-16 19:28:59 +00007198 // For the LHS, do usual unary conversions, but then reset them away
7199 // if this is a compound assignment.
John Wiegley429bb272011-04-08 18:41:53 +00007200 ExprResult old_lex = lex;
7201 lex = UsualUnaryConversions(lex.take());
7202 if (lex.isInvalid())
7203 return QualType();
7204 QualType LHSTy = lex.get()->getType();
John McCall1bc80af2010-12-16 19:28:59 +00007205 if (isCompAssign) lex = old_lex;
7206
7207 // The RHS is simpler.
John Wiegley429bb272011-04-08 18:41:53 +00007208 rex = UsualUnaryConversions(rex.take());
7209 if (rex.isInvalid())
7210 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007211
Ryan Flynnd0439682009-08-07 16:20:20 +00007212 // Sanity-check shift operands
Chandler Carruth21206d52011-02-23 23:34:11 +00007213 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnd0439682009-08-07 16:20:20 +00007214
Chris Lattnerca5eede2007-12-12 05:47:28 +00007215 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00007216 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007217}
7218
Chandler Carruth99919472010-07-10 12:30:03 +00007219static bool IsWithinTemplateSpecialization(Decl *D) {
7220 if (DeclContext *DC = D->getDeclContext()) {
7221 if (isa<ClassTemplateSpecializationDecl>(DC))
7222 return true;
7223 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7224 return FD->isFunctionTemplateSpecialization();
7225 }
7226 return false;
7227}
7228
Douglas Gregor0c6db942009-05-04 06:07:12 +00007229// C99 6.5.8, C++ [expr.rel]
John Wiegley429bb272011-04-08 18:41:53 +00007230QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00007231 unsigned OpaqueOpc, bool isRelational) {
John McCall2de56d12010-08-25 11:45:40 +00007232 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00007233
Chris Lattner02dd4b12009-12-05 05:40:13 +00007234 // Handle vector comparisons separately.
John Wiegley429bb272011-04-08 18:41:53 +00007235 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007236 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007237
John Wiegley429bb272011-04-08 18:41:53 +00007238 QualType lType = lex.get()->getType();
7239 QualType rType = rex.get()->getType();
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007240
John Wiegley429bb272011-04-08 18:41:53 +00007241 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
7242 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00007243 QualType LHSStrippedType = LHSStripped->getType();
7244 QualType RHSStrippedType = RHSStripped->getType();
7245
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007246
7247
Chandler Carruth543cb652011-02-17 08:37:06 +00007248 // Two different enums will raise a warning when compared.
7249 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
7250 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
7251 if (LHSEnumType->getDecl()->getIdentifier() &&
7252 RHSEnumType->getDecl()->getIdentifier() &&
7253 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
7254 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7255 << LHSStrippedType << RHSStrippedType
John Wiegley429bb272011-04-08 18:41:53 +00007256 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth543cb652011-02-17 08:37:06 +00007257 }
7258 }
7259 }
7260
Douglas Gregor8eee1192010-06-22 22:12:46 +00007261 if (!lType->hasFloatingRepresentation() &&
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00007262 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley429bb272011-04-08 18:41:53 +00007263 !lex.get()->getLocStart().isMacroID() &&
7264 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00007265 // For non-floating point types, check for self-comparisons of the form
7266 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7267 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00007268 //
7269 // NOTE: Don't warn about comparison expressions resulting from macro
7270 // expansion. Also don't warn about comparisons which are only self
7271 // comparisons within a template specialization. The warnings should catch
7272 // obvious cases in the definition of the template anyways. The idea is to
7273 // warn when the typed comparison operator will always evaluate to the same
7274 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00007275 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00007276 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00007277 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00007278 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00007279 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00007280 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00007281 << (Opc == BO_EQ
7282 || Opc == BO_LE
7283 || Opc == BO_GE));
Douglas Gregord64fdd02010-06-08 19:50:34 +00007284 } else if (lType->isArrayType() && rType->isArrayType() &&
7285 !DRL->getDecl()->getType()->isReferenceType() &&
7286 !DRR->getDecl()->getType()->isReferenceType()) {
7287 // what is it always going to eval to?
7288 char always_evals_to;
7289 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007290 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00007291 always_evals_to = 0; // false
7292 break;
John McCall2de56d12010-08-25 11:45:40 +00007293 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00007294 always_evals_to = 1; // true
7295 break;
7296 default:
7297 // best we can say is 'a constant'
7298 always_evals_to = 2; // e.g. array1 <= array2
7299 break;
7300 }
Ted Kremenek351ba912011-02-23 01:52:04 +00007301 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00007302 << 1 // array
7303 << always_evals_to);
7304 }
7305 }
Chandler Carruth99919472010-07-10 12:30:03 +00007306 }
Mike Stump1eb44332009-09-09 15:08:12 +00007307
Chris Lattner55660a72009-03-08 19:39:53 +00007308 if (isa<CastExpr>(LHSStripped))
7309 LHSStripped = LHSStripped->IgnoreParenCasts();
7310 if (isa<CastExpr>(RHSStripped))
7311 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00007312
Chris Lattner55660a72009-03-08 19:39:53 +00007313 // Warn about comparisons against a string constant (unless the other
7314 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00007315 Expr *literalString = 0;
7316 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00007317 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007318 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007319 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00007320 literalString = lex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007321 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00007322 } else if ((isa<StringLiteral>(RHSStripped) ||
7323 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007324 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007325 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00007326 literalString = rex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007327 literalStringStripped = RHSStripped;
7328 }
7329
7330 if (literalString) {
7331 std::string resultComparison;
7332 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007333 case BO_LT: resultComparison = ") < 0"; break;
7334 case BO_GT: resultComparison = ") > 0"; break;
7335 case BO_LE: resultComparison = ") <= 0"; break;
7336 case BO_GE: resultComparison = ") >= 0"; break;
7337 case BO_EQ: resultComparison = ") == 0"; break;
7338 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00007339 default: assert(false && "Invalid comparison operator");
7340 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007341
Ted Kremenek351ba912011-02-23 01:52:04 +00007342 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00007343 PDiag(diag::warn_stringcompare)
7344 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00007345 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00007346 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00007347 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007348
Douglas Gregord64fdd02010-06-08 19:50:34 +00007349 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley429bb272011-04-08 18:41:53 +00007350 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00007351 UsualArithmeticConversions(lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00007352 if (lex.isInvalid() || rex.isInvalid())
7353 return QualType();
7354 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00007355 else {
John Wiegley429bb272011-04-08 18:41:53 +00007356 lex = UsualUnaryConversions(lex.take());
7357 if (lex.isInvalid())
7358 return QualType();
7359
7360 rex = UsualUnaryConversions(rex.take());
7361 if (rex.isInvalid())
7362 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007363 }
7364
John Wiegley429bb272011-04-08 18:41:53 +00007365 lType = lex.get()->getType();
7366 rType = rex.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007367
Douglas Gregor447b69e2008-11-19 03:25:36 +00007368 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00007369 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00007370
Chris Lattnera5937dd2007-08-26 01:18:55 +00007371 if (isRelational) {
7372 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007373 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007374 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00007375 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007376 if (lType->hasFloatingRepresentation())
John Wiegley429bb272011-04-08 18:41:53 +00007377 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007378
Chris Lattnera5937dd2007-08-26 01:18:55 +00007379 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007380 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007381 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007382
John Wiegley429bb272011-04-08 18:41:53 +00007383 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007384 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00007385 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007386 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007387
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007388 // All of the following pointer-related warnings are GCC extensions, except
7389 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00007390 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00007391 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00007392 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00007393 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00007394 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007395
Douglas Gregor0c6db942009-05-04 06:07:12 +00007396 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00007397 if (LCanPointeeTy == RCanPointeeTy)
7398 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007399 if (!isRelational &&
7400 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7401 // Valid unless comparison between non-null pointer and function pointer
7402 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007403 // In a SFINAE context, we treat this as a hard error to maintain
7404 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007405 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7406 && !LHSIsNull && !RHSIsNull) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007407 Diag(Loc,
7408 isSFINAEContext()?
7409 diag::err_typecheck_comparison_of_fptr_to_void
7410 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley429bb272011-04-08 18:41:53 +00007411 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007412
7413 if (isSFINAEContext())
7414 return QualType();
7415
John Wiegley429bb272011-04-08 18:41:53 +00007416 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007417 return ResultTy;
7418 }
7419 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007420
Douglas Gregor0c6db942009-05-04 06:07:12 +00007421 // C++ [expr.rel]p2:
7422 // [...] Pointer conversions (4.10) and qualification
7423 // conversions (4.4) are performed on pointer operands (or on
7424 // a pointer operand and a null pointer constant) to bring
7425 // them to their composite pointer type. [...]
7426 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00007427 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00007428 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007429 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00007430 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007431 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00007432 if (T.isNull()) {
7433 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007434 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00007435 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007436 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007437 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007438 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007439 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00007440 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00007441 }
7442
John Wiegley429bb272011-04-08 18:41:53 +00007443 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7444 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00007445 return ResultTy;
7446 }
Eli Friedman3075e762009-08-23 00:27:47 +00007447 // C99 6.5.9p2 and C99 6.5.8p2
7448 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7449 RCanPointeeTy.getUnqualifiedType())) {
7450 // Valid unless a relational comparison of function pointers
7451 if (isRelational && LCanPointeeTy->isFunctionType()) {
7452 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007453 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007454 }
7455 } else if (!isRelational &&
7456 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7457 // Valid unless comparison between non-null pointer and function pointer
7458 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7459 && !LHSIsNull && !RHSIsNull) {
7460 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley429bb272011-04-08 18:41:53 +00007461 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007462 }
7463 } else {
7464 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007465 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007466 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007467 }
John McCall34d6f932011-03-11 04:25:25 +00007468 if (LCanPointeeTy != RCanPointeeTy) {
7469 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007470 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007471 else
John Wiegley429bb272011-04-08 18:41:53 +00007472 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007473 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007474 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007475 }
Mike Stump1eb44332009-09-09 15:08:12 +00007476
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007477 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007478 // Comparison of nullptr_t with itself.
7479 if (lType->isNullPtrType() && rType->isNullPtrType())
7480 return ResultTy;
7481
Mike Stump1eb44332009-09-09 15:08:12 +00007482 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007483 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007484 if (RHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007485 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00007486 (!isRelational && lType->isMemberPointerType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00007487 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregor443c2122010-08-07 13:36:37 +00007488 lType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007489 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007490 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007491 return ResultTy;
7492 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007493 if (LHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007494 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00007495 (!isRelational && rType->isMemberPointerType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00007496 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregor443c2122010-08-07 13:36:37 +00007497 rType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007498 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007499 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007500 return ResultTy;
7501 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007502
7503 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00007504 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00007505 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7506 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00007507 // In addition, pointers to members can be compared, or a pointer to
7508 // member and a null pointer constant. Pointer to member conversions
7509 // (4.11) and qualification conversions (4.4) are performed to bring
7510 // them to a common type. If one operand is a null pointer constant,
7511 // the common type is the type of the other operand. Otherwise, the
7512 // common type is a pointer to member type similar (4.4) to the type
7513 // of one of the operands, with a cv-qualification signature (4.4)
7514 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00007515 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007516 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00007517 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007518 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00007519 if (T.isNull()) {
7520 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007521 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00007522 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007523 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007524 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007525 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007526 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00007527 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00007528 }
Mike Stump1eb44332009-09-09 15:08:12 +00007529
John Wiegley429bb272011-04-08 18:41:53 +00007530 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7531 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00007532 return ResultTy;
7533 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007534
7535 // Handle scoped enumeration types specifically, since they don't promote
7536 // to integers.
John Wiegley429bb272011-04-08 18:41:53 +00007537 if (lex.get()->getType()->isEnumeralType() &&
7538 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007539 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007540 }
Mike Stump1eb44332009-09-09 15:08:12 +00007541
Steve Naroff1c7d0672008-09-04 15:10:53 +00007542 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00007543 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00007544 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7545 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007546
Steve Naroff1c7d0672008-09-04 15:10:53 +00007547 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007548 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007549 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley429bb272011-04-08 18:41:53 +00007550 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007551 }
John Wiegley429bb272011-04-08 18:41:53 +00007552 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007553 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007554 }
John Wiegley429bb272011-04-08 18:41:53 +00007555
Steve Naroff59f53942008-09-28 01:11:11 +00007556 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00007557 if (!isRelational
7558 && ((lType->isBlockPointerType() && rType->isPointerType())
7559 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007560 if (!LHSIsNull && !RHSIsNull) {
John McCall34d6f932011-03-11 04:25:25 +00007561 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007562 ->getPointeeType()->isVoidType())
John McCall34d6f932011-03-11 04:25:25 +00007563 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007564 ->getPointeeType()->isVoidType())))
7565 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley429bb272011-04-08 18:41:53 +00007566 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007567 }
John McCall34d6f932011-03-11 04:25:25 +00007568 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007569 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007570 else
John Wiegley429bb272011-04-08 18:41:53 +00007571 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007572 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007573 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007574
John McCall34d6f932011-03-11 04:25:25 +00007575 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7576 const PointerType *LPT = lType->getAs<PointerType>();
7577 const PointerType *RPT = rType->getAs<PointerType>();
7578 if (LPT || RPT) {
7579 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7580 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007581
Steve Naroffa8069f12008-11-17 19:49:16 +00007582 if (!LPtrToVoid && !RPtrToVoid &&
7583 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007584 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007585 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00007586 }
John McCall34d6f932011-03-11 04:25:25 +00007587 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007588 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007589 else
John Wiegley429bb272011-04-08 18:41:53 +00007590 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007591 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007592 }
Steve Naroff14108da2009-07-10 23:34:53 +00007593 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007594 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00007595 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007596 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall34d6f932011-03-11 04:25:25 +00007597 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007598 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007599 else
John Wiegley429bb272011-04-08 18:41:53 +00007600 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007601 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007602 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007603 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007604 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7605 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007606 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007607 bool isError = false;
7608 if ((LHSIsNull && lType->isIntegerType()) ||
7609 (RHSIsNull && rType->isIntegerType())) {
7610 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007611 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007612 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007613 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007614 else if (getLangOptions().CPlusPlus) {
7615 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7616 isError = true;
7617 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007618 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007619
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007620 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007621 Diag(Loc, DiagID)
John Wiegley429bb272011-04-08 18:41:53 +00007622 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007623 if (isError)
7624 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007625 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007626
7627 if (lType->isIntegerType())
John Wiegley429bb272011-04-08 18:41:53 +00007628 lex = ImpCastExprToType(lex.take(), rType,
John McCall404cd162010-11-13 01:35:44 +00007629 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007630 else
John Wiegley429bb272011-04-08 18:41:53 +00007631 rex = ImpCastExprToType(rex.take(), lType,
John McCall404cd162010-11-13 01:35:44 +00007632 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007633 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007634 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007635
Steve Naroff39218df2008-09-04 16:56:14 +00007636 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00007637 if (!isRelational && RHSIsNull
7638 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00007639 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007640 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007641 }
Mike Stumpaf199f32009-05-07 18:43:07 +00007642 if (!isRelational && LHSIsNull
7643 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00007644 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007645 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007646 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007647
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007648 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007649}
7650
Nate Begemanbe2341d2008-07-14 18:02:46 +00007651/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007652/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007653/// like a scalar comparison, a vector comparison produces a vector of integer
7654/// types.
John Wiegley429bb272011-04-08 18:41:53 +00007655QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007656 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007657 bool isRelational) {
7658 // Check to make sure we're operating on vectors of the same type and width,
7659 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007660 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007661 if (vType.isNull())
7662 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007663
John Wiegley429bb272011-04-08 18:41:53 +00007664 QualType lType = lex.get()->getType();
7665 QualType rType = rex.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007666
Anton Yartsev7870b132011-03-27 15:36:07 +00007667 // If AltiVec, the comparison results in a numeric type, i.e.
7668 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007669 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007670 return Context.getLogicalOperationType();
7671
Nate Begemanbe2341d2008-07-14 18:02:46 +00007672 // For non-floating point types, check for self-comparisons of the form
7673 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7674 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007675 if (!lType->hasFloatingRepresentation()) {
John Wiegley429bb272011-04-08 18:41:53 +00007676 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
7677 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007678 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007679 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007680 PDiag(diag::warn_comparison_always)
7681 << 0 // self-
7682 << 2 // "a constant"
7683 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007684 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007685
Nate Begemanbe2341d2008-07-14 18:02:46 +00007686 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007687 if (!isRelational && lType->hasFloatingRepresentation()) {
7688 assert (rType->hasFloatingRepresentation());
John Wiegley429bb272011-04-08 18:41:53 +00007689 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007690 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007691
Nate Begemanbe2341d2008-07-14 18:02:46 +00007692 // Return the type for the comparison, which is the same as vector type for
7693 // integer vectors, or an integer type of identical size and number of
7694 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00007695 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00007696 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007697
John McCall183700f2009-09-21 23:43:11 +00007698 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00007699 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00007700 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007701 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00007702 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00007703 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7704
Mike Stumpeed9cac2009-02-19 03:04:26 +00007705 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00007706 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00007707 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7708}
7709
Reid Spencer5f016e22007-07-11 17:01:13 +00007710inline QualType Sema::CheckBitwiseOperands(
John Wiegley429bb272011-04-08 18:41:53 +00007711 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
7712 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
7713 if (lex.get()->getType()->hasIntegerRepresentation() &&
7714 rex.get()->getType()->hasIntegerRepresentation())
Douglas Gregorf6094622010-07-23 15:58:24 +00007715 return CheckVectorOperands(Loc, lex, rex);
7716
7717 return InvalidOperands(Loc, lex, rex);
7718 }
Steve Naroff90045e82007-07-13 23:32:42 +00007719
John Wiegley429bb272011-04-08 18:41:53 +00007720 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
7721 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
7722 if (lexResult.isInvalid() || rexResult.isInvalid())
7723 return QualType();
7724 lex = lexResult.take();
7725 rex = rexResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007726
John Wiegley429bb272011-04-08 18:41:53 +00007727 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
7728 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007729 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007730 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007731}
7732
7733inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley429bb272011-04-08 18:41:53 +00007734 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00007735
7736 // Diagnose cases where the user write a logical and/or but probably meant a
7737 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7738 // is a constant.
John Wiegley429bb272011-04-08 18:41:53 +00007739 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
7740 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Chris Lattner23ef3e42010-07-15 00:26:43 +00007741 // Don't warn in macros.
Chris Lattnerb7690b42010-07-24 01:10:11 +00007742 !Loc.isMacroID()) {
7743 // If the RHS can be constant folded, and if it constant folds to something
7744 // that isn't 0 or 1 (which indicate a potential logical operation that
7745 // happened to fold to true/false) then warn.
7746 Expr::EvalResult Result;
John Wiegley429bb272011-04-08 18:41:53 +00007747 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects &&
Chris Lattnerb7690b42010-07-24 01:10:11 +00007748 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7749 Diag(Loc, diag::warn_logical_instead_of_bitwise)
John Wiegley429bb272011-04-08 18:41:53 +00007750 << rex.get()->getSourceRange()
John McCall2de56d12010-08-25 11:45:40 +00007751 << (Opc == BO_LAnd ? "&&" : "||")
7752 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattnerb7690b42010-07-24 01:10:11 +00007753 }
7754 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007755
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007756 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007757 lex = UsualUnaryConversions(lex.take());
7758 if (lex.isInvalid())
7759 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007760
John Wiegley429bb272011-04-08 18:41:53 +00007761 rex = UsualUnaryConversions(rex.take());
7762 if (rex.isInvalid())
7763 return QualType();
7764
7765 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007766 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007767
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007768 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007769 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007770
John McCall75f7c0f2010-06-04 00:29:51 +00007771 // The following is safe because we only use this method for
7772 // non-overloadable operands.
7773
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007774 // C++ [expr.log.and]p1
7775 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007776 // The operands are both contextually converted to type bool.
John Wiegley429bb272011-04-08 18:41:53 +00007777 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
7778 if (lexRes.isInvalid())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007779 return InvalidOperands(Loc, lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00007780 lex = move(lexRes);
7781
7782 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
7783 if (rexRes.isInvalid())
7784 return InvalidOperands(Loc, lex, rex);
7785 rex = move(rexRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007786
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007787 // C++ [expr.log.and]p2
7788 // C++ [expr.log.or]p2
7789 // The result is a bool.
7790 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007791}
7792
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007793/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7794/// is a read-only property; return true if so. A readonly property expression
7795/// depends on various declarations and thus must be treated specially.
7796///
Mike Stump1eb44332009-09-09 15:08:12 +00007797static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007798 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7799 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00007800 if (PropExpr->isImplicitProperty()) return false;
7801
7802 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7803 QualType BaseType = PropExpr->isSuperReceiver() ?
7804 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007805 PropExpr->getBase()->getType();
7806
John McCall12f78a62010-12-02 01:19:52 +00007807 if (const ObjCObjectPointerType *OPT =
7808 BaseType->getAsObjCInterfacePointerType())
7809 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7810 if (S.isPropertyReadonly(PDecl, IFace))
7811 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007812 }
7813 return false;
7814}
7815
Fariborz Jahanian14086762011-03-28 23:47:18 +00007816static bool IsConstProperty(Expr *E, Sema &S) {
7817 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7818 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7819 if (PropExpr->isImplicitProperty()) return false;
7820
7821 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7822 QualType T = PDecl->getType();
7823 if (T->isReferenceType())
Fariborz Jahanian61750f22011-03-30 16:59:30 +00007824 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanian14086762011-03-28 23:47:18 +00007825 CanQualType CT = S.Context.getCanonicalType(T);
7826 return CT.isConstQualified();
7827 }
7828 return false;
7829}
7830
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007831static bool IsReadonlyMessage(Expr *E, Sema &S) {
7832 if (E->getStmtClass() != Expr::MemberExprClass)
7833 return false;
7834 const MemberExpr *ME = cast<MemberExpr>(E);
7835 NamedDecl *Member = ME->getMemberDecl();
7836 if (isa<FieldDecl>(Member)) {
7837 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7838 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7839 return false;
7840 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7841 }
7842 return false;
7843}
7844
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007845/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7846/// emit an error and return true. If so, return false.
7847static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007848 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007849 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007850 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007851 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7852 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian14086762011-03-28 23:47:18 +00007853 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7854 IsLV = Expr::MLV_Valid;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007855 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7856 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007857 if (IsLV == Expr::MLV_Valid)
7858 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007859
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007860 unsigned Diag = 0;
7861 bool NeedType = false;
7862 switch (IsLV) { // C99 6.5.16p2
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007863 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007864 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007865 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7866 NeedType = true;
7867 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007868 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007869 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7870 NeedType = true;
7871 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007872 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007873 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7874 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007875 case Expr::MLV_Valid:
7876 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007877 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007878 case Expr::MLV_MemberFunction:
7879 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007880 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7881 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007882 case Expr::MLV_IncompleteType:
7883 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007884 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007885 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00007886 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00007887 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007888 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7889 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00007890 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007891 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7892 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007893 case Expr::MLV_ReadonlyProperty:
7894 Diag = diag::error_readonly_property_assignment;
7895 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007896 case Expr::MLV_NoSetterProperty:
7897 Diag = diag::error_nosetter_property_assignment;
7898 break;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007899 case Expr::MLV_InvalidMessageExpression:
7900 Diag = diag::error_readonly_message_assignment;
7901 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007902 case Expr::MLV_SubObjCPropertySetting:
7903 Diag = diag::error_no_subobject_property_setting;
7904 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007905 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007906
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007907 SourceRange Assign;
7908 if (Loc != OrigLoc)
7909 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007910 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007911 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007912 else
Mike Stump1eb44332009-09-09 15:08:12 +00007913 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007914 return true;
7915}
7916
7917
7918
7919// C99 6.5.16.1
John Wiegley429bb272011-04-08 18:41:53 +00007920QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007921 SourceLocation Loc,
7922 QualType CompoundType) {
7923 // Verify that LHS is a modifiable lvalue, and emit error if not.
7924 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007925 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007926
7927 QualType LHSType = LHS->getType();
John Wiegley429bb272011-04-08 18:41:53 +00007928 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007929 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007930 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007931 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007932 // Simple assignment "x = y".
John Wiegley429bb272011-04-08 18:41:53 +00007933 if (LHS->getObjectKind() == OK_ObjCProperty) {
7934 ExprResult LHSResult = Owned(LHS);
7935 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7936 if (LHSResult.isInvalid())
7937 return QualType();
7938 LHS = LHSResult.take();
7939 }
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007940 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007941 if (RHS.isInvalid())
7942 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007943 // Special case of NSObject attributes on c-style pointer types.
7944 if (ConvTy == IncompatiblePointer &&
7945 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007946 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007947 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007948 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007949 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007950
John McCallf89e55a2010-11-18 06:31:45 +00007951 if (ConvTy == Compatible &&
7952 getLangOptions().ObjCNonFragileABI &&
7953 LHSType->isObjCObjectType())
7954 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7955 << LHSType;
7956
Chris Lattner2c156472008-08-21 18:04:13 +00007957 // If the RHS is a unary plus or minus, check to see if they = and + are
7958 // right next to each other. If so, the user may have typo'd "x =+ 4"
7959 // instead of "x += 4".
John Wiegley429bb272011-04-08 18:41:53 +00007960 Expr *RHSCheck = RHS.get();
Chris Lattner2c156472008-08-21 18:04:13 +00007961 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7962 RHSCheck = ICE->getSubExpr();
7963 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007964 if ((UO->getOpcode() == UO_Plus ||
7965 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007966 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007967 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00007968 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7969 // And there is a space or other character before the subexpr of the
7970 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00007971 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7972 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007973 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007974 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007975 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007976 }
Chris Lattner2c156472008-08-21 18:04:13 +00007977 }
7978 } else {
7979 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007980 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007981 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007982
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007983 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007984 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007985 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007986
Chris Lattner8b5dec32010-07-07 06:14:23 +00007987
7988 // Check to see if the destination operand is a dereferenced null pointer. If
7989 // so, and if not volatile-qualified, this is undefined behavior that the
7990 // optimizer will delete, so warn about it. People sometimes try to use this
7991 // to get a deterministic trap and are surprised by clang's behavior. This
7992 // only handles the pattern "*null = whatever", which is a very syntactic
7993 // check.
7994 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCall2de56d12010-08-25 11:45:40 +00007995 if (UO->getOpcode() == UO_Deref &&
Chris Lattner8b5dec32010-07-07 06:14:23 +00007996 UO->getSubExpr()->IgnoreParenCasts()->
7997 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
7998 !UO->getType().isVolatileQualified()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00007999 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
8000 PDiag(diag::warn_indirection_through_null)
8001 << UO->getSubExpr()->getSourceRange());
8002 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
8003 PDiag(diag::note_indirection_through_null));
Chris Lattner8b5dec32010-07-07 06:14:23 +00008004 }
8005
Ted Kremeneka0125d82011-02-16 01:57:07 +00008006 // Check for trivial buffer overflows.
Ted Kremenek3aea4da2011-03-01 18:41:00 +00008007 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremeneka0125d82011-02-16 01:57:07 +00008008
Reid Spencer5f016e22007-07-11 17:01:13 +00008009 // C99 6.5.16p3: The type of an assignment expression is the type of the
8010 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00008011 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00008012 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8013 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008014 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00008015 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00008016 return (getLangOptions().CPlusPlus
8017 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008018}
8019
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008020// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00008021static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00008022 SourceLocation Loc) {
John Wiegley429bb272011-04-08 18:41:53 +00008023 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00008024
John McCallfb8721c2011-04-10 19:13:55 +00008025 LHS = S.CheckPlaceholderExpr(LHS.take());
8026 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00008027 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00008028 return QualType();
8029
John McCallcf2e5062010-10-12 07:14:40 +00008030 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8031 // operands, but not unary promotions.
8032 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008033
John McCallf6a16482010-12-04 03:47:34 +00008034 // So we treat the LHS as a ignored value, and in C++ we allow the
8035 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00008036 LHS = S.IgnoredValueConversions(LHS.take());
8037 if (LHS.isInvalid())
8038 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00008039
8040 if (!S.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00008041 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8042 if (RHS.isInvalid())
8043 return QualType();
8044 if (!RHS.get()->getType()->isVoidType())
8045 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00008046 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008047
John Wiegley429bb272011-04-08 18:41:53 +00008048 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008049}
8050
Steve Naroff49b45262007-07-13 16:58:59 +00008051/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8052/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00008053static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8054 ExprValueKind &VK,
8055 SourceLocation OpLoc,
8056 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00008057 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008058 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008059
Chris Lattner3528d352008-11-21 07:05:48 +00008060 QualType ResType = Op->getType();
8061 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008062
John McCall09431682010-11-18 19:01:18 +00008063 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00008064 // Decrement of bool is not allowed.
8065 if (!isInc) {
John McCall09431682010-11-18 19:01:18 +00008066 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00008067 return QualType();
8068 }
8069 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00008070 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00008071 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00008072 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00008073 } else if (ResType->isAnyPointerType()) {
8074 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00008075
Chris Lattner3528d352008-11-21 07:05:48 +00008076 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00008077 if (PointeeTy->isVoidType()) {
John McCall09431682010-11-18 19:01:18 +00008078 if (S.getLangOptions().CPlusPlus) {
8079 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00008080 << Op->getSourceRange();
8081 return QualType();
8082 }
8083
8084 // Pointer to void is a GNU extension in C.
John McCall09431682010-11-18 19:01:18 +00008085 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00008086 } else if (PointeeTy->isFunctionType()) {
John McCall09431682010-11-18 19:01:18 +00008087 if (S.getLangOptions().CPlusPlus) {
8088 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00008089 << Op->getType() << Op->getSourceRange();
8090 return QualType();
8091 }
8092
John McCall09431682010-11-18 19:01:18 +00008093 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00008094 << ResType << Op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00008095 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
8096 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00008097 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00008098 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00008099 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00008100 // Diagnose bad cases where we step over interface counts.
John McCall09431682010-11-18 19:01:18 +00008101 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
8102 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00008103 << PointeeTy << Op->getSourceRange();
8104 return QualType();
8105 }
Eli Friedman5b088a12010-01-03 00:20:48 +00008106 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00008107 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00008108 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00008109 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008110 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008111 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008112 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008113 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8114 isInc, isPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00008115 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
8116 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00008117 } else {
John McCall09431682010-11-18 19:01:18 +00008118 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00008119 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00008120 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008121 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008122 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00008123 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00008124 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00008125 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008126 // In C++, a prefix increment is the same type as the operand. Otherwise
8127 // (in C or with postfix), the increment is the unqualified type of the
8128 // operand.
John McCall09431682010-11-18 19:01:18 +00008129 if (isPrefix && S.getLangOptions().CPlusPlus) {
8130 VK = VK_LValue;
8131 return ResType;
8132 } else {
8133 VK = VK_RValue;
8134 return ResType.getUnqualifiedType();
8135 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008136}
8137
John Wiegley429bb272011-04-08 18:41:53 +00008138ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCallf6a16482010-12-04 03:47:34 +00008139 assert(E->getValueKind() == VK_LValue &&
8140 E->getObjectKind() == OK_ObjCProperty);
8141 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
8142
8143 ExprValueKind VK = VK_RValue;
8144 if (PRE->isImplicitProperty()) {
Fariborz Jahanian99130e52010-12-22 19:46:35 +00008145 if (const ObjCMethodDecl *GetterMethod =
8146 PRE->getImplicitPropertyGetter()) {
8147 QualType Result = GetterMethod->getResultType();
8148 VK = Expr::getValueKindForType(Result);
8149 }
8150 else {
8151 Diag(PRE->getLocation(), diag::err_getter_not_found)
8152 << PRE->getBase()->getType();
8153 }
John McCallf6a16482010-12-04 03:47:34 +00008154 }
8155
8156 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
8157 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00008158
8159 ExprResult Result = MaybeBindToTemporary(E);
8160 if (!Result.isInvalid())
8161 E = Result.take();
John Wiegley429bb272011-04-08 18:41:53 +00008162
8163 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00008164}
8165
John Wiegley429bb272011-04-08 18:41:53 +00008166void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
8167 assert(LHS.get()->getValueKind() == VK_LValue &&
8168 LHS.get()->getObjectKind() == OK_ObjCProperty);
8169 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCallf6a16482010-12-04 03:47:34 +00008170
John Wiegley429bb272011-04-08 18:41:53 +00008171 if (PropRef->isImplicitProperty()) {
John McCallf6a16482010-12-04 03:47:34 +00008172 // If using property-dot syntax notation for assignment, and there is a
8173 // setter, RHS expression is being passed to the setter argument. So,
8174 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley429bb272011-04-08 18:41:53 +00008175 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCallf6a16482010-12-04 03:47:34 +00008176 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
8177 LHSTy = (*P)->getType();
8178
8179 // Otherwise, if the getter returns an l-value, just call that.
8180 } else {
John Wiegley429bb272011-04-08 18:41:53 +00008181 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCallf6a16482010-12-04 03:47:34 +00008182 ExprValueKind VK = Expr::getValueKindForType(Result);
8183 if (VK == VK_LValue) {
John Wiegley429bb272011-04-08 18:41:53 +00008184 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
8185 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCallf6a16482010-12-04 03:47:34 +00008186 return;
John McCall12f78a62010-12-02 01:19:52 +00008187 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008188 }
John McCallf6a16482010-12-04 03:47:34 +00008189 }
8190
8191 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008192 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00008193 InitializedEntity::InitializeParameter(Context, LHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00008194 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008195 if (!ArgE.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00008196 RHS = ArgE;
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008197 }
8198}
8199
8200
Anders Carlsson369dee42008-02-01 07:15:58 +00008201/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00008202/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008203/// where the declaration is needed for type checking. We only need to
8204/// handle cases when the expression references a function designator
8205/// or is an lvalue. Here are some examples:
8206/// - &(x) => x
8207/// - &*****f => f for f a function designator.
8208/// - &s.xx => s
8209/// - &s.zz[1].yy -> s, if zz is an array
8210/// - *(x + 1) -> x, if x is an array
8211/// - &"123"[2] -> 0
8212/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00008213static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00008214 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00008215 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00008216 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00008217 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00008218 // If this is an arrow operator, the address is an offset from
8219 // the base's value, so the object the base refers to is
8220 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00008221 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00008222 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00008223 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00008224 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00008225 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00008226 // FIXME: This code shouldn't be necessary! We should catch the implicit
8227 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00008228 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8229 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8230 if (ICE->getSubExpr()->getType()->isArrayType())
8231 return getPrimaryDecl(ICE->getSubExpr());
8232 }
8233 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00008234 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008235 case Stmt::UnaryOperatorClass: {
8236 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008237
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008238 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00008239 case UO_Real:
8240 case UO_Imag:
8241 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008242 return getPrimaryDecl(UO->getSubExpr());
8243 default:
8244 return 0;
8245 }
8246 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008247 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00008248 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00008249 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00008250 // If the result of an implicit cast is an l-value, we care about
8251 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00008252 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00008253 default:
8254 return 0;
8255 }
8256}
8257
8258/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00008259/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00008260/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008261/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00008262/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008263/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00008264/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00008265static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
8266 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00008267 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008268 return S.Context.DependentTy;
8269 if (OrigOp->getType() == S.Context.OverloadTy)
8270 return S.Context.OverloadTy;
John McCall755d8492011-04-12 00:42:48 +00008271 if (OrigOp->getType() == S.Context.UnknownAnyTy)
8272 return S.Context.UnknownAnyTy;
John McCall9c72c602010-08-27 09:08:28 +00008273
John McCall755d8492011-04-12 00:42:48 +00008274 assert(!OrigOp->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00008275
John McCall9c72c602010-08-27 09:08:28 +00008276 // Make sure to ignore parentheses in subsequent checks
8277 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00008278
John McCall09431682010-11-18 19:01:18 +00008279 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00008280 // Implement C99-only parts of addressof rules.
8281 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00008282 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00008283 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8284 // (assuming the deref expression is valid).
8285 return uOp->getSubExpr()->getType();
8286 }
8287 // Technically, there should be a check for array subscript
8288 // expressions here, but the result of one is always an lvalue anyway.
8289 }
John McCall5808ce42011-02-03 08:15:49 +00008290 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00008291 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00008292
Fariborz Jahanian077f4902011-03-26 19:48:30 +00008293 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00008294 bool sfinae = S.isSFINAEContext();
8295 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8296 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00008297 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00008298 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00008299 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00008300 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008301 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00008302 } else if (lval == Expr::LV_MemberFunction) {
8303 // If it's an instance method, make a member pointer.
8304 // The expression must have exactly the form &A::foo.
8305
8306 // If the underlying expression isn't a decl ref, give up.
8307 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008308 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008309 << OrigOp->getSourceRange();
8310 return QualType();
8311 }
8312 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8313 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8314
8315 // The id-expression was parenthesized.
8316 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00008317 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008318 << OrigOp->getSourceRange();
8319
8320 // The method was named without a qualifier.
8321 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00008322 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008323 << op->getSourceRange();
8324 }
8325
John McCall09431682010-11-18 19:01:18 +00008326 return S.Context.getMemberPointerType(op->getType(),
8327 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00008328 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00008329 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008330 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00008331 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00008332 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00008333 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008334 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00008335 return QualType();
8336 }
John McCall7eb0a9e2010-11-24 05:12:34 +00008337 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008338 // The operand cannot be a bit-field
John McCall09431682010-11-18 19:01:18 +00008339 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman23d58ce2009-04-20 08:23:18 +00008340 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00008341 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00008342 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00008343 // The operand cannot be an element of a vector
John McCall09431682010-11-18 19:01:18 +00008344 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00008345 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00008346 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00008347 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00008348 // cannot take address of a property expression.
John McCall09431682010-11-18 19:01:18 +00008349 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian0337f212009-07-07 18:50:52 +00008350 << "property expression" << op->getSourceRange();
8351 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00008352 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00008353 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00008354 // with the register storage-class specifier.
8355 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00008356 // in C++ it is not error to take address of a register
8357 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00008358 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00008359 !S.getLangOptions().CPlusPlus) {
8360 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008361 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00008362 return QualType();
8363 }
John McCallba135432009-11-21 08:51:07 +00008364 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00008365 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00008366 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00008367 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00008368 // Could be a pointer to member, though, if there is an explicit
8369 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00008370 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00008371 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008372 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00008373 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00008374 S.Diag(OpLoc,
8375 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00008376 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008377 return QualType();
8378 }
Mike Stump1eb44332009-09-09 15:08:12 +00008379
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00008380 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8381 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00008382 return S.Context.getMemberPointerType(op->getType(),
8383 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008384 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00008385 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00008386 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00008387 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00008388 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00008389
Eli Friedman441cf102009-05-16 23:27:50 +00008390 if (lval == Expr::LV_IncompleteVoidType) {
8391 // Taking the address of a void variable is technically illegal, but we
8392 // allow it in cases which are otherwise valid.
8393 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00008394 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00008395 }
8396
Reid Spencer5f016e22007-07-11 17:01:13 +00008397 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00008398 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00008399 return S.Context.getObjCObjectPointerType(op->getType());
8400 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008401}
8402
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008403/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00008404static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8405 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00008406 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008407 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008408
John Wiegley429bb272011-04-08 18:41:53 +00008409 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8410 if (ConvResult.isInvalid())
8411 return QualType();
8412 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008413 QualType OpTy = Op->getType();
8414 QualType Result;
8415
8416 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8417 // is an incomplete type or void. It would be possible to warn about
8418 // dereferencing a void pointer, but it's completely well-defined, and such a
8419 // warning is unlikely to catch any mistakes.
8420 if (const PointerType *PT = OpTy->getAs<PointerType>())
8421 Result = PT->getPointeeType();
8422 else if (const ObjCObjectPointerType *OPT =
8423 OpTy->getAs<ObjCObjectPointerType>())
8424 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008425 else {
John McCallfb8721c2011-04-10 19:13:55 +00008426 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008427 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008428 if (PR.take() != Op)
8429 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008430 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008431
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008432 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008433 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008434 << OpTy << Op->getSourceRange();
8435 return QualType();
8436 }
John McCall09431682010-11-18 19:01:18 +00008437
8438 // Dereferences are usually l-values...
8439 VK = VK_LValue;
8440
8441 // ...except that certain expressions are never l-values in C.
8442 if (!S.getLangOptions().CPlusPlus &&
8443 IsCForbiddenLValueType(S.Context, Result))
8444 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008445
8446 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008447}
8448
John McCall2de56d12010-08-25 11:45:40 +00008449static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008450 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008451 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008452 switch (Kind) {
8453 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008454 case tok::periodstar: Opc = BO_PtrMemD; break;
8455 case tok::arrowstar: Opc = BO_PtrMemI; break;
8456 case tok::star: Opc = BO_Mul; break;
8457 case tok::slash: Opc = BO_Div; break;
8458 case tok::percent: Opc = BO_Rem; break;
8459 case tok::plus: Opc = BO_Add; break;
8460 case tok::minus: Opc = BO_Sub; break;
8461 case tok::lessless: Opc = BO_Shl; break;
8462 case tok::greatergreater: Opc = BO_Shr; break;
8463 case tok::lessequal: Opc = BO_LE; break;
8464 case tok::less: Opc = BO_LT; break;
8465 case tok::greaterequal: Opc = BO_GE; break;
8466 case tok::greater: Opc = BO_GT; break;
8467 case tok::exclaimequal: Opc = BO_NE; break;
8468 case tok::equalequal: Opc = BO_EQ; break;
8469 case tok::amp: Opc = BO_And; break;
8470 case tok::caret: Opc = BO_Xor; break;
8471 case tok::pipe: Opc = BO_Or; break;
8472 case tok::ampamp: Opc = BO_LAnd; break;
8473 case tok::pipepipe: Opc = BO_LOr; break;
8474 case tok::equal: Opc = BO_Assign; break;
8475 case tok::starequal: Opc = BO_MulAssign; break;
8476 case tok::slashequal: Opc = BO_DivAssign; break;
8477 case tok::percentequal: Opc = BO_RemAssign; break;
8478 case tok::plusequal: Opc = BO_AddAssign; break;
8479 case tok::minusequal: Opc = BO_SubAssign; break;
8480 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8481 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8482 case tok::ampequal: Opc = BO_AndAssign; break;
8483 case tok::caretequal: Opc = BO_XorAssign; break;
8484 case tok::pipeequal: Opc = BO_OrAssign; break;
8485 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008486 }
8487 return Opc;
8488}
8489
John McCall2de56d12010-08-25 11:45:40 +00008490static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008491 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008492 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008493 switch (Kind) {
8494 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008495 case tok::plusplus: Opc = UO_PreInc; break;
8496 case tok::minusminus: Opc = UO_PreDec; break;
8497 case tok::amp: Opc = UO_AddrOf; break;
8498 case tok::star: Opc = UO_Deref; break;
8499 case tok::plus: Opc = UO_Plus; break;
8500 case tok::minus: Opc = UO_Minus; break;
8501 case tok::tilde: Opc = UO_Not; break;
8502 case tok::exclaim: Opc = UO_LNot; break;
8503 case tok::kw___real: Opc = UO_Real; break;
8504 case tok::kw___imag: Opc = UO_Imag; break;
8505 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008506 }
8507 return Opc;
8508}
8509
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008510/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8511/// This warning is only emitted for builtin assignment operations. It is also
8512/// suppressed in the event of macro expansions.
8513static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8514 SourceLocation OpLoc) {
8515 if (!S.ActiveTemplateInstantiations.empty())
8516 return;
8517 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8518 return;
8519 lhs = lhs->IgnoreParenImpCasts();
8520 rhs = rhs->IgnoreParenImpCasts();
8521 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8522 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8523 if (!LeftDeclRef || !RightDeclRef ||
8524 LeftDeclRef->getLocation().isMacroID() ||
8525 RightDeclRef->getLocation().isMacroID())
8526 return;
8527 const ValueDecl *LeftDecl =
8528 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8529 const ValueDecl *RightDecl =
8530 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8531 if (LeftDecl != RightDecl)
8532 return;
8533 if (LeftDecl->getType().isVolatileQualified())
8534 return;
8535 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8536 if (RefTy->getPointeeType().isVolatileQualified())
8537 return;
8538
8539 S.Diag(OpLoc, diag::warn_self_assignment)
8540 << LeftDeclRef->getType()
8541 << lhs->getSourceRange() << rhs->getSourceRange();
8542}
8543
Douglas Gregoreaebc752008-11-06 23:29:22 +00008544/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8545/// operator @p Opc at location @c TokLoc. This routine only supports
8546/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008547ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008548 BinaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008549 Expr *lhsExpr, Expr *rhsExpr) {
8550 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008551 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008552 // The following two variables are used for compound assignment operators
8553 QualType CompLHSTy; // Type of LHS after promotions for computation
8554 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008555 ExprValueKind VK = VK_RValue;
8556 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008557
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008558 // Check if a 'foo<int>' involved in a binary op, identifies a single
8559 // function unambiguously (i.e. an lvalue ala 13.4)
8560 // But since an assignment can trigger target based overload, exclude it in
8561 // our blind search. i.e:
8562 // template<class T> void f(); template<class T, class U> void f(U);
8563 // f<int> == 0; // resolve f<int> blindly
8564 // void (*p)(int); p = f<int>; // resolve f<int> using target
8565 if (Opc != BO_Assign) {
John McCallfb8721c2011-04-10 19:13:55 +00008566 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008567 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008568 lhs = move(resolvedLHS);
John McCall1de4d4e2011-04-07 08:22:57 +00008569
John McCallfb8721c2011-04-10 19:13:55 +00008570 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008571 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008572 rhs = move(resolvedRHS);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008573 }
8574
Douglas Gregoreaebc752008-11-06 23:29:22 +00008575 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008576 case BO_Assign:
John Wiegley429bb272011-04-08 18:41:53 +00008577 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00008578 if (getLangOptions().CPlusPlus &&
John Wiegley429bb272011-04-08 18:41:53 +00008579 lhs.get()->getObjectKind() != OK_ObjCProperty) {
8580 VK = lhs.get()->getValueKind();
8581 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008582 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008583 if (!ResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00008584 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008585 break;
John McCall2de56d12010-08-25 11:45:40 +00008586 case BO_PtrMemD:
8587 case BO_PtrMemI:
John McCallf89e55a2010-11-18 06:31:45 +00008588 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008589 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008590 break;
John McCall2de56d12010-08-25 11:45:40 +00008591 case BO_Mul:
8592 case BO_Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00008593 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008594 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008595 break;
John McCall2de56d12010-08-25 11:45:40 +00008596 case BO_Rem:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008597 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
8598 break;
John McCall2de56d12010-08-25 11:45:40 +00008599 case BO_Add:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008600 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
8601 break;
John McCall2de56d12010-08-25 11:45:40 +00008602 case BO_Sub:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008603 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
8604 break;
John McCall2de56d12010-08-25 11:45:40 +00008605 case BO_Shl:
8606 case BO_Shr:
Chandler Carruth21206d52011-02-23 23:34:11 +00008607 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008608 break;
John McCall2de56d12010-08-25 11:45:40 +00008609 case BO_LE:
8610 case BO_LT:
8611 case BO_GE:
8612 case BO_GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00008613 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008614 break;
John McCall2de56d12010-08-25 11:45:40 +00008615 case BO_EQ:
8616 case BO_NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00008617 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008618 break;
John McCall2de56d12010-08-25 11:45:40 +00008619 case BO_And:
8620 case BO_Xor:
8621 case BO_Or:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008622 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8623 break;
John McCall2de56d12010-08-25 11:45:40 +00008624 case BO_LAnd:
8625 case BO_LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00008626 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008627 break;
John McCall2de56d12010-08-25 11:45:40 +00008628 case BO_MulAssign:
8629 case BO_DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00008630 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008631 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008632 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00008633 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8634 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008635 break;
John McCall2de56d12010-08-25 11:45:40 +00008636 case BO_RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008637 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
8638 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00008639 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8640 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008641 break;
John McCall2de56d12010-08-25 11:45:40 +00008642 case BO_AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008643 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00008644 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8645 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008646 break;
John McCall2de56d12010-08-25 11:45:40 +00008647 case BO_SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008648 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00008649 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8650 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008651 break;
John McCall2de56d12010-08-25 11:45:40 +00008652 case BO_ShlAssign:
8653 case BO_ShrAssign:
Chandler Carruth21206d52011-02-23 23:34:11 +00008654 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008655 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00008656 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8657 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008658 break;
John McCall2de56d12010-08-25 11:45:40 +00008659 case BO_AndAssign:
8660 case BO_XorAssign:
8661 case BO_OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008662 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8663 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00008664 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8665 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008666 break;
John McCall2de56d12010-08-25 11:45:40 +00008667 case BO_Comma:
John McCall09431682010-11-18 19:01:18 +00008668 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00008669 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
8670 VK = rhs.get()->getValueKind();
8671 OK = rhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008672 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008673 break;
8674 }
John Wiegley429bb272011-04-08 18:41:53 +00008675 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008676 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00008677 if (CompResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00008678 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
8679 ResultTy, VK, OK, OpLoc));
8680 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008681 VK = VK_LValue;
John Wiegley429bb272011-04-08 18:41:53 +00008682 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008683 }
John Wiegley429bb272011-04-08 18:41:53 +00008684 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
8685 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00008686 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008687}
8688
Sebastian Redlaee3c932009-10-27 12:10:02 +00008689/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8690/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008691static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8692 const PartialDiagnostic &PD,
Douglas Gregor55b38842010-04-14 16:09:52 +00008693 const PartialDiagnostic &FirstNote,
8694 SourceRange FirstParenRange,
8695 const PartialDiagnostic &SecondNote,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008696 SourceRange SecondParenRange) {
Douglas Gregor55b38842010-04-14 16:09:52 +00008697 Self.Diag(Loc, PD);
8698
8699 if (!FirstNote.getDiagID())
8700 return;
8701
8702 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8703 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8704 // We can't display the parentheses, so just return.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008705 return;
8706 }
8707
Douglas Gregor55b38842010-04-14 16:09:52 +00008708 Self.Diag(Loc, FirstNote)
8709 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregor849b2432010-03-31 17:46:05 +00008710 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008711
Douglas Gregor55b38842010-04-14 16:09:52 +00008712 if (!SecondNote.getDiagID())
Douglas Gregor827feec2010-01-08 00:20:23 +00008713 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008714
Douglas Gregor827feec2010-01-08 00:20:23 +00008715 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8716 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8717 // We can't display the parentheses, so just dig the
8718 // warning/error and return.
Douglas Gregor55b38842010-04-14 16:09:52 +00008719 Self.Diag(Loc, SecondNote);
Douglas Gregor827feec2010-01-08 00:20:23 +00008720 return;
8721 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008722
Douglas Gregor55b38842010-04-14 16:09:52 +00008723 Self.Diag(Loc, SecondNote)
Douglas Gregor849b2432010-03-31 17:46:05 +00008724 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8725 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008726}
8727
Sebastian Redlaee3c932009-10-27 12:10:02 +00008728/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8729/// operators are mixed in a way that suggests that the programmer forgot that
8730/// comparison operators have higher precedence. The most typical example of
8731/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008732static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008733 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00008734 typedef BinaryOperator BinOp;
8735 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8736 rhsopc = static_cast<BinOp::Opcode>(-1);
8737 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008738 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00008739 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008740 rhsopc = BO->getOpcode();
8741
8742 // Subs are not binary operators.
8743 if (lhsopc == -1 && rhsopc == -1)
8744 return;
8745
8746 // Bitwise operations are sometimes used as eager logical ops.
8747 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00008748 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8749 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008750 return;
8751
Sebastian Redlaee3c932009-10-27 12:10:02 +00008752 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008753 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008754 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00008755 << SourceRange(lhs->getLocStart(), OpLoc)
8756 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008757 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00008758 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00008759 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
8760 Self.PDiag(diag::note_precedence_bitwise_silence)
8761 << BinOp::getOpcodeStr(lhsopc),
8762 lhs->getSourceRange());
Sebastian Redlaee3c932009-10-27 12:10:02 +00008763 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008764 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008765 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00008766 << SourceRange(OpLoc, rhs->getLocEnd())
8767 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008768 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00008769 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00008770 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
8771 Self.PDiag(diag::note_precedence_bitwise_silence)
8772 << BinOp::getOpcodeStr(rhsopc),
8773 rhs->getSourceRange());
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008774}
8775
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008776/// \brief It accepts a '&&' expr that is inside a '||' one.
8777/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8778/// in parentheses.
8779static void
8780EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8781 Expr *E) {
8782 assert(isa<BinaryOperator>(E) &&
8783 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
8784 SuggestParentheses(Self, OpLoc,
8785 Self.PDiag(diag::warn_logical_and_in_logical_or)
8786 << E->getSourceRange(),
8787 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8788 E->getSourceRange(),
8789 Self.PDiag(0), SourceRange());
8790}
8791
8792/// \brief Returns true if the given expression can be evaluated as a constant
8793/// 'true'.
8794static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8795 bool Res;
8796 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8797}
8798
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008799/// \brief Returns true if the given expression can be evaluated as a constant
8800/// 'false'.
8801static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8802 bool Res;
8803 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8804}
8805
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008806/// \brief Look for '&&' in the left hand of a '||' expr.
8807static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008808 Expr *OrLHS, Expr *OrRHS) {
8809 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008810 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008811 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8812 if (EvaluatesAsFalse(S, OrRHS))
8813 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008814 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8815 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8816 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8817 } else if (Bop->getOpcode() == BO_LOr) {
8818 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8819 // If it's "a || b && 1 || c" we didn't warn earlier for
8820 // "a || b && 1", but warn now.
8821 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8822 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8823 }
8824 }
8825 }
8826}
8827
8828/// \brief Look for '&&' in the right hand of a '||' expr.
8829static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008830 Expr *OrLHS, Expr *OrRHS) {
8831 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008832 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008833 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8834 if (EvaluatesAsFalse(S, OrLHS))
8835 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008836 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8837 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8838 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008839 }
8840 }
8841}
8842
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008843/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008844/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008845static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008846 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008847 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008848 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008849 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8850
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008851 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8852 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008853 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008854 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8855 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008856 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008857}
8858
Reid Spencer5f016e22007-07-11 17:01:13 +00008859// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008860ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008861 tok::TokenKind Kind,
8862 Expr *lhs, Expr *rhs) {
8863 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Narofff69936d2007-09-16 03:34:24 +00008864 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8865 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008866
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008867 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8868 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8869
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008870 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8871}
8872
John McCall60d7b3a2010-08-24 06:29:42 +00008873ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008874 BinaryOperatorKind Opc,
8875 Expr *lhs, Expr *rhs) {
John McCall01b2e4e2010-12-06 05:26:58 +00008876 if (getLangOptions().CPlusPlus) {
8877 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008878
John McCall01b2e4e2010-12-06 05:26:58 +00008879 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8880 UseBuiltinOperator = false;
8881 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8882 UseBuiltinOperator = true;
8883 } else {
8884 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8885 !rhs->getType()->isOverloadableType();
8886 }
8887
8888 if (!UseBuiltinOperator) {
8889 // Find all of the overloaded operators visible from this
8890 // point. We perform both an operator-name lookup from the local
8891 // scope and an argument-dependent lookup based on the types of
8892 // the arguments.
8893 UnresolvedSet<16> Functions;
8894 OverloadedOperatorKind OverOp
8895 = BinaryOperator::getOverloadedOperator(Opc);
8896 if (S && OverOp != OO_None)
8897 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8898 Functions);
8899
8900 // Build the (potentially-overloaded, potentially-dependent)
8901 // binary operation.
8902 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8903 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008904 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008905
Douglas Gregoreaebc752008-11-06 23:29:22 +00008906 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008907 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00008908}
8909
John McCall60d7b3a2010-08-24 06:29:42 +00008910ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008911 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008912 Expr *InputExpr) {
8913 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008914 ExprValueKind VK = VK_RValue;
8915 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008916 QualType resultType;
8917 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008918 case UO_PreInc:
8919 case UO_PreDec:
8920 case UO_PostInc:
8921 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008922 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008923 Opc == UO_PreInc ||
8924 Opc == UO_PostInc,
8925 Opc == UO_PreInc ||
8926 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008927 break;
John McCall2de56d12010-08-25 11:45:40 +00008928 case UO_AddrOf:
John Wiegley429bb272011-04-08 18:41:53 +00008929 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008930 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008931 case UO_Deref: {
John McCallfb8721c2011-04-10 19:13:55 +00008932 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008933 if (!resolved.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008934 Input = move(resolved);
8935 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8936 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008937 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008938 }
John McCall2de56d12010-08-25 11:45:40 +00008939 case UO_Plus:
8940 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008941 Input = UsualUnaryConversions(Input.take());
8942 if (Input.isInvalid()) return ExprError();
8943 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008944 if (resultType->isDependentType())
8945 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008946 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8947 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008948 break;
8949 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8950 resultType->isEnumeralType())
8951 break;
8952 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008953 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008954 resultType->isPointerType())
8955 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008956 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008957 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008958 if (Input.isInvalid()) return ExprError();
8959 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008960 }
Douglas Gregor74253732008-11-19 15:42:04 +00008961
Sebastian Redl0eb23302009-01-19 00:08:26 +00008962 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008963 << resultType << Input.get()->getSourceRange());
8964
John McCall2de56d12010-08-25 11:45:40 +00008965 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008966 Input = UsualUnaryConversions(Input.take());
8967 if (Input.isInvalid()) return ExprError();
8968 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008969 if (resultType->isDependentType())
8970 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008971 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8972 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8973 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008974 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008975 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008976 else if (resultType->hasIntegerRepresentation())
8977 break;
8978 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008979 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008980 if (Input.isInvalid()) return ExprError();
8981 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008982 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008983 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008984 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008985 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008986 break;
John Wiegley429bb272011-04-08 18:41:53 +00008987
John McCall2de56d12010-08-25 11:45:40 +00008988 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008989 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008990 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8991 if (Input.isInvalid()) return ExprError();
8992 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008993 if (resultType->isDependentType())
8994 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008995 if (resultType->isScalarType()) {
8996 // C99 6.5.3.3p1: ok, fallthrough;
8997 if (Context.getLangOptions().CPlusPlus) {
8998 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8999 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00009000 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9001 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00009002 }
John McCall2cd11fe2010-10-12 02:09:17 +00009003 } else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00009004 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00009005 if (Input.isInvalid()) return ExprError();
9006 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00009007 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00009008 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00009009 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00009010 }
Douglas Gregorea844f32010-09-20 17:13:33 +00009011
Reid Spencer5f016e22007-07-11 17:01:13 +00009012 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00009013 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00009014 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00009015 break;
John McCall2de56d12010-08-25 11:45:40 +00009016 case UO_Real:
9017 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00009018 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00009019 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley429bb272011-04-08 18:41:53 +00009020 if (Input.isInvalid()) return ExprError();
9021 if (Input.get()->getValueKind() != VK_RValue &&
9022 Input.get()->getObjectKind() == OK_Ordinary)
9023 VK = Input.get()->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00009024 break;
John McCall2de56d12010-08-25 11:45:40 +00009025 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00009026 resultType = Input.get()->getType();
9027 VK = Input.get()->getValueKind();
9028 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00009029 break;
9030 }
John Wiegley429bb272011-04-08 18:41:53 +00009031 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00009032 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009033
John Wiegley429bb272011-04-08 18:41:53 +00009034 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00009035 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00009036}
9037
John McCall60d7b3a2010-08-24 06:29:42 +00009038ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00009039 UnaryOperatorKind Opc,
9040 Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00009041 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00009042 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009043 // Find all of the overloaded operators visible from this
9044 // point. We perform both an operator-name lookup from the local
9045 // scope and an argument-dependent lookup based on the types of
9046 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00009047 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009048 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00009049 if (S && OverOp != OO_None)
9050 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9051 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009052
John McCall9ae2f072010-08-23 23:25:46 +00009053 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009054 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009055
John McCall9ae2f072010-08-23 23:25:46 +00009056 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009057}
9058
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009059// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00009060ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00009061 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00009062 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009063}
9064
Steve Naroff1b273c42007-09-16 14:56:35 +00009065/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009066ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00009067 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009068 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00009069 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009070 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009071 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00009072}
9073
John McCall60d7b3a2010-08-24 06:29:42 +00009074ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00009075Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009076 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009077 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9078 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9079
Douglas Gregordd8f5692010-03-10 04:54:39 +00009080 bool isFileScope
9081 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00009082 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00009083 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00009084
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009085 // FIXME: there are a variety of strange constraints to enforce here, for
9086 // example, it is not possible to goto into a stmt expression apparently.
9087 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009088
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009089 // If there are sub stmts in the compound stmt, take the type of the last one
9090 // as the type of the stmtexpr.
9091 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009092 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009093 if (!Compound->body_empty()) {
9094 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009095 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009096 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009097 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9098 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009099 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009100 }
John Wiegley429bb272011-04-08 18:41:53 +00009101 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00009102 // Do function/array conversion on the last expression, but not
9103 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00009104 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9105 if (LastExpr.isInvalid())
9106 return ExprError();
9107 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00009108
John Wiegley429bb272011-04-08 18:41:53 +00009109 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9110 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009111 InitializedEntity::InitializeResult(LPLoc,
9112 Ty,
9113 false),
9114 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00009115 LastExpr);
9116 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009117 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009118 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009119 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00009120 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009121 else
John Wiegley429bb272011-04-08 18:41:53 +00009122 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009123 StmtExprMayBindToTemp = true;
9124 }
9125 }
9126 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00009127 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009128
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009129 // FIXME: Check that expression type is complete/non-abstract; statement
9130 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009131 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9132 if (StmtExprMayBindToTemp)
9133 return MaybeBindToTemporary(ResStmtExpr);
9134 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009135}
Steve Naroffd34e9152007-08-01 22:05:33 +00009136
John McCall60d7b3a2010-08-24 06:29:42 +00009137ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009138 TypeSourceInfo *TInfo,
9139 OffsetOfComponent *CompPtr,
9140 unsigned NumComponents,
9141 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009142 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009143 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009144 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009145
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009146 // We must have at least one component that refers to the type, and the first
9147 // one is known to be a field designator. Verify that the ArgTy represents
9148 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00009149 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009150 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9151 << ArgTy << TypeRange);
9152
9153 // Type must be complete per C99 7.17p3 because a declaring a variable
9154 // with an incomplete type would be ill-formed.
9155 if (!Dependent
9156 && RequireCompleteType(BuiltinLoc, ArgTy,
9157 PDiag(diag::err_offsetof_incomplete_type)
9158 << TypeRange))
9159 return ExprError();
9160
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009161 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9162 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00009163 // FIXME: This diagnostic isn't actually visible because the location is in
9164 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009165 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00009166 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9167 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009168
9169 bool DidWarnAboutNonPOD = false;
9170 QualType CurrentType = ArgTy;
9171 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9172 llvm::SmallVector<OffsetOfNode, 4> Comps;
9173 llvm::SmallVector<Expr*, 4> Exprs;
9174 for (unsigned i = 0; i != NumComponents; ++i) {
9175 const OffsetOfComponent &OC = CompPtr[i];
9176 if (OC.isBrackets) {
9177 // Offset of an array sub-field. TODO: Should we allow vector elements?
9178 if (!CurrentType->isDependentType()) {
9179 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9180 if(!AT)
9181 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9182 << CurrentType);
9183 CurrentType = AT->getElementType();
9184 } else
9185 CurrentType = Context.DependentTy;
9186
9187 // The expression must be an integral expression.
9188 // FIXME: An integral constant expression?
9189 Expr *Idx = static_cast<Expr*>(OC.U.E);
9190 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9191 !Idx->getType()->isIntegerType())
9192 return ExprError(Diag(Idx->getLocStart(),
9193 diag::err_typecheck_subscript_not_integer)
9194 << Idx->getSourceRange());
9195
9196 // Record this array index.
9197 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9198 Exprs.push_back(Idx);
9199 continue;
9200 }
9201
9202 // Offset of a field.
9203 if (CurrentType->isDependentType()) {
9204 // We have the offset of a field, but we can't look into the dependent
9205 // type. Just record the identifier of the field.
9206 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9207 CurrentType = Context.DependentTy;
9208 continue;
9209 }
9210
9211 // We need to have a complete type to look into.
9212 if (RequireCompleteType(OC.LocStart, CurrentType,
9213 diag::err_offsetof_incomplete_type))
9214 return ExprError();
9215
9216 // Look for the designated field.
9217 const RecordType *RC = CurrentType->getAs<RecordType>();
9218 if (!RC)
9219 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9220 << CurrentType);
9221 RecordDecl *RD = RC->getDecl();
9222
9223 // C++ [lib.support.types]p5:
9224 // The macro offsetof accepts a restricted set of type arguments in this
9225 // International Standard. type shall be a POD structure or a POD union
9226 // (clause 9).
9227 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9228 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009229 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009230 PDiag(diag::warn_offsetof_non_pod_type)
9231 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9232 << CurrentType))
9233 DidWarnAboutNonPOD = true;
9234 }
9235
9236 // Look for the field.
9237 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9238 LookupQualifiedName(R, RD);
9239 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009240 IndirectFieldDecl *IndirectMemberDecl = 0;
9241 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009242 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009243 MemberDecl = IndirectMemberDecl->getAnonField();
9244 }
9245
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009246 if (!MemberDecl)
9247 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9248 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9249 OC.LocEnd));
9250
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009251 // C99 7.17p3:
9252 // (If the specified member is a bit-field, the behavior is undefined.)
9253 //
9254 // We diagnose this as an error.
9255 if (MemberDecl->getBitWidth()) {
9256 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9257 << MemberDecl->getDeclName()
9258 << SourceRange(BuiltinLoc, RParenLoc);
9259 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9260 return ExprError();
9261 }
Eli Friedman19410a72010-08-05 10:11:36 +00009262
9263 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009264 if (IndirectMemberDecl)
9265 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009266
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009267 // If the member was found in a base class, introduce OffsetOfNodes for
9268 // the base class indirections.
9269 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9270 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009271 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009272 CXXBasePath &Path = Paths.front();
9273 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9274 B != BEnd; ++B)
9275 Comps.push_back(OffsetOfNode(B->Base));
9276 }
Eli Friedman19410a72010-08-05 10:11:36 +00009277
Francois Pichet87c2e122010-11-21 06:08:52 +00009278 if (IndirectMemberDecl) {
9279 for (IndirectFieldDecl::chain_iterator FI =
9280 IndirectMemberDecl->chain_begin(),
9281 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9282 assert(isa<FieldDecl>(*FI));
9283 Comps.push_back(OffsetOfNode(OC.LocStart,
9284 cast<FieldDecl>(*FI), OC.LocEnd));
9285 }
9286 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009287 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009288
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009289 CurrentType = MemberDecl->getType().getNonReferenceType();
9290 }
9291
9292 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9293 TInfo, Comps.data(), Comps.size(),
9294 Exprs.data(), Exprs.size(), RParenLoc));
9295}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009296
John McCall60d7b3a2010-08-24 06:29:42 +00009297ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009298 SourceLocation BuiltinLoc,
9299 SourceLocation TypeLoc,
9300 ParsedType argty,
9301 OffsetOfComponent *CompPtr,
9302 unsigned NumComponents,
9303 SourceLocation RPLoc) {
9304
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009305 TypeSourceInfo *ArgTInfo;
9306 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
9307 if (ArgTy.isNull())
9308 return ExprError();
9309
Eli Friedman5a15dc12010-08-05 10:15:45 +00009310 if (!ArgTInfo)
9311 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9312
9313 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9314 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009315}
9316
9317
John McCall60d7b3a2010-08-24 06:29:42 +00009318ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009319 Expr *CondExpr,
9320 Expr *LHSExpr, Expr *RHSExpr,
9321 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009322 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9323
John McCallf89e55a2010-11-18 06:31:45 +00009324 ExprValueKind VK = VK_RValue;
9325 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009326 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009327 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009328 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009329 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009330 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009331 } else {
9332 // The conditional expression is required to be a constant expression.
9333 llvm::APSInt condEval(32);
9334 SourceLocation ExpLoc;
9335 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00009336 return ExprError(Diag(ExpLoc,
9337 diag::err_typecheck_choose_expr_requires_constant)
9338 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00009339
Sebastian Redl28507842009-02-26 14:39:58 +00009340 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009341 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9342
9343 resType = ActiveExpr->getType();
9344 ValueDependent = ActiveExpr->isValueDependent();
9345 VK = ActiveExpr->getValueKind();
9346 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009347 }
9348
Sebastian Redlf53597f2009-03-15 17:47:39 +00009349 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009350 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009351 resType->isDependentType(),
9352 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009353}
9354
Steve Naroff4eb206b2008-09-03 18:15:37 +00009355//===----------------------------------------------------------------------===//
9356// Clang Extensions.
9357//===----------------------------------------------------------------------===//
9358
9359/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00009360void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009361 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9362 PushBlockScope(BlockScope, Block);
9363 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009364 if (BlockScope)
9365 PushDeclContext(BlockScope, Block);
9366 else
9367 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00009368}
9369
Mike Stump98eb8a72009-02-04 22:31:32 +00009370void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009371 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009372 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009373 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009374
John McCallbf1a0282010-06-04 23:28:52 +00009375 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009376 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009377
John McCall711c52b2011-01-05 12:14:39 +00009378 // GetTypeForDeclarator always produces a function type for a block
9379 // literal signature. Furthermore, it is always a FunctionProtoType
9380 // unless the function was written with a typedef.
9381 assert(T->isFunctionType() &&
9382 "GetTypeForDeclarator made a non-function block signature");
9383
9384 // Look for an explicit signature in that function type.
9385 FunctionProtoTypeLoc ExplicitSignature;
9386
9387 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9388 if (isa<FunctionProtoTypeLoc>(tmp)) {
9389 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9390
9391 // Check whether that explicit signature was synthesized by
9392 // GetTypeForDeclarator. If so, don't save that as part of the
9393 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009394 if (ExplicitSignature.getLocalRangeBegin() ==
9395 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009396 // This would be much cheaper if we stored TypeLocs instead of
9397 // TypeSourceInfos.
9398 TypeLoc Result = ExplicitSignature.getResultLoc();
9399 unsigned Size = Result.getFullDataSize();
9400 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9401 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9402
9403 ExplicitSignature = FunctionProtoTypeLoc();
9404 }
John McCall82dc0092010-06-04 11:21:44 +00009405 }
Mike Stump1eb44332009-09-09 15:08:12 +00009406
John McCall711c52b2011-01-05 12:14:39 +00009407 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9408 CurBlock->FunctionType = T;
9409
9410 const FunctionType *Fn = T->getAs<FunctionType>();
9411 QualType RetTy = Fn->getResultType();
9412 bool isVariadic =
9413 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9414
John McCallc71a4912010-06-04 19:02:56 +00009415 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009416
John McCall82dc0092010-06-04 11:21:44 +00009417 // Don't allow returning a objc interface by value.
9418 if (RetTy->isObjCObjectType()) {
9419 Diag(ParamInfo.getSourceRange().getBegin(),
9420 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9421 return;
9422 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009423
John McCall82dc0092010-06-04 11:21:44 +00009424 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009425 // return type. TODO: what should we do with declarators like:
9426 // ^ * { ... }
9427 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00009428 if (RetTy != Context.DependentTy)
9429 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009430
John McCall82dc0092010-06-04 11:21:44 +00009431 // Push block parameters from the declarator if we had them.
John McCallc71a4912010-06-04 19:02:56 +00009432 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009433 if (ExplicitSignature) {
9434 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9435 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009436 if (Param->getIdentifier() == 0 &&
9437 !Param->isImplicit() &&
9438 !Param->isInvalidDecl() &&
9439 !getLangOptions().CPlusPlus)
9440 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009441 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009442 }
John McCall82dc0092010-06-04 11:21:44 +00009443
9444 // Fake up parameter variables if we have a typedef, like
9445 // ^ fntype { ... }
9446 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9447 for (FunctionProtoType::arg_type_iterator
9448 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9449 ParmVarDecl *Param =
9450 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9451 ParamInfo.getSourceRange().getBegin(),
9452 *I);
John McCallc71a4912010-06-04 19:02:56 +00009453 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009454 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009455 }
John McCall82dc0092010-06-04 11:21:44 +00009456
John McCallc71a4912010-06-04 19:02:56 +00009457 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009458 if (!Params.empty()) {
John McCallc71a4912010-06-04 19:02:56 +00009459 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregor82aa7132010-11-01 18:37:59 +00009460 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9461 CurBlock->TheDecl->param_end(),
9462 /*CheckParameterNames=*/false);
9463 }
9464
John McCall82dc0092010-06-04 11:21:44 +00009465 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009466 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009467
John McCallc71a4912010-06-04 19:02:56 +00009468 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00009469 Diag(ParamInfo.getAttributes()->getLoc(),
9470 diag::warn_attribute_sentinel_not_variadic) << 1;
9471 // FIXME: remove the attribute.
9472 }
9473
9474 // Put the parameter variables in scope. We can bail out immediately
9475 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009476 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009477 return;
9478
Steve Naroff090276f2008-10-10 01:28:17 +00009479 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009480 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9481 (*AI)->setOwningFunction(CurBlock->TheDecl);
9482
Steve Naroff090276f2008-10-10 01:28:17 +00009483 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009484 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009485 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009486
Steve Naroff090276f2008-10-10 01:28:17 +00009487 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009488 }
John McCall7a9813c2010-01-22 00:28:27 +00009489 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009490}
9491
9492/// ActOnBlockError - If there is an error parsing a block, this callback
9493/// is invoked to pop the information about the block from the action impl.
9494void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00009495 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009496 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009497 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009498}
9499
9500/// ActOnBlockStmtExpr - This is called when the body of a block statement
9501/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009502ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009503 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009504 // If blocks are disabled, emit an error.
9505 if (!LangOpts.Blocks)
9506 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009507
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009508 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009509
Steve Naroff090276f2008-10-10 01:28:17 +00009510 PopDeclContext();
9511
Steve Naroff4eb206b2008-09-03 18:15:37 +00009512 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009513 if (!BSI->ReturnType.isNull())
9514 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009515
Mike Stump56925862009-07-28 22:04:01 +00009516 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009517 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009518
John McCall469a1eb2011-02-02 13:00:07 +00009519 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00009520 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
9521 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00009522
John McCallc71a4912010-06-04 19:02:56 +00009523 // If the user wrote a function type in some form, try to use that.
9524 if (!BSI->FunctionType.isNull()) {
9525 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9526
9527 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9528 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9529
9530 // Turn protoless block types into nullary block types.
9531 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009532 FunctionProtoType::ExtProtoInfo EPI;
9533 EPI.ExtInfo = Ext;
9534 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009535
9536 // Otherwise, if we don't need to change anything about the function type,
9537 // preserve its sugar structure.
9538 } else if (FTy->getResultType() == RetTy &&
9539 (!NoReturn || FTy->getNoReturnAttr())) {
9540 BlockTy = BSI->FunctionType;
9541
9542 // Otherwise, make the minimal modifications to the function type.
9543 } else {
9544 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009545 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9546 EPI.TypeQuals = 0; // FIXME: silently?
9547 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009548 BlockTy = Context.getFunctionType(RetTy,
9549 FPT->arg_type_begin(),
9550 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009551 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009552 }
9553
9554 // If we don't have a function type, just build one from nothing.
9555 } else {
John McCalle23cf432010-12-14 08:05:40 +00009556 FunctionProtoType::ExtProtoInfo EPI;
Eli Friedmana49218e2011-04-09 08:18:08 +00009557 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, false, 0, CC_Default);
John McCalle23cf432010-12-14 08:05:40 +00009558 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009559 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009560
John McCallc71a4912010-06-04 19:02:56 +00009561 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9562 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009563 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009564
Chris Lattner17a78302009-04-19 05:28:12 +00009565 // If needed, diagnose invalid gotos and switches in the block.
John McCall781472f2010-08-25 08:40:02 +00009566 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00009567 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009568
Chris Lattnere476bdc2011-02-17 23:58:47 +00009569 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009570
John McCall469a1eb2011-02-02 13:00:07 +00009571 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCalle0054f62010-08-25 05:56:39 +00009572
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009573 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9574 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009575 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009576}
9577
John McCall60d7b3a2010-08-24 06:29:42 +00009578ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallb3d87482010-08-24 05:47:05 +00009579 Expr *expr, ParsedType type,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009580 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009581 TypeSourceInfo *TInfo;
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009582 GetTypeFromParser(type, &TInfo);
John McCall9ae2f072010-08-23 23:25:46 +00009583 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009584}
9585
John McCall60d7b3a2010-08-24 06:29:42 +00009586ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00009587 Expr *E, TypeSourceInfo *TInfo,
9588 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009589 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00009590
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009591 // Get the va_list type
9592 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009593 if (VaListType->isArrayType()) {
9594 // Deal with implicit array decay; for example, on x86-64,
9595 // va_list is an array, but it's supposed to decay to
9596 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009597 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00009598 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00009599 ExprResult Result = UsualUnaryConversions(E);
9600 if (Result.isInvalid())
9601 return ExprError();
9602 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009603 } else {
9604 // Otherwise, the va_list argument must be an l-value because
9605 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00009606 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00009607 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00009608 return ExprError();
9609 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009610
Douglas Gregordd027302009-05-19 23:10:31 +00009611 if (!E->isTypeDependent() &&
9612 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00009613 return ExprError(Diag(E->getLocStart(),
9614 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009615 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00009616 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009617
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009618 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009619 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009620
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009621 QualType T = TInfo->getType().getNonLValueExprType(Context);
9622 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009623}
9624
John McCall60d7b3a2010-08-24 06:29:42 +00009625ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009626 // The type of __null will be int or long, depending on the size of
9627 // pointers on the target.
9628 QualType Ty;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009629 unsigned pw = Context.Target.getPointerWidth(0);
9630 if (pw == Context.Target.getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009631 Ty = Context.IntTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009632 else if (pw == Context.Target.getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009633 Ty = Context.LongTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009634 else if (pw == Context.Target.getLongLongWidth())
9635 Ty = Context.LongLongTy;
9636 else {
9637 assert(!"I don't know size of pointer!");
9638 Ty = Context.IntTy;
9639 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009640
Sebastian Redlf53597f2009-03-15 17:47:39 +00009641 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009642}
9643
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009644static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009645 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009646 if (!SemaRef.getLangOptions().ObjC1)
9647 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009648
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009649 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9650 if (!PT)
9651 return;
9652
9653 // Check if the destination is of type 'id'.
9654 if (!PT->isObjCIdType()) {
9655 // Check if the destination is the 'NSString' interface.
9656 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9657 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9658 return;
9659 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009660
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009661 // Strip off any parens and casts.
9662 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9663 if (!SL || SL->isWide())
9664 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009665
Douglas Gregor849b2432010-03-31 17:46:05 +00009666 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009667}
9668
Chris Lattner5cf216b2008-01-04 18:04:52 +00009669bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9670 SourceLocation Loc,
9671 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009672 Expr *SrcExpr, AssignmentAction Action,
9673 bool *Complained) {
9674 if (Complained)
9675 *Complained = false;
9676
Chris Lattner5cf216b2008-01-04 18:04:52 +00009677 // Decode the result (notice that AST's are still created for extensions).
9678 bool isInvalid = false;
9679 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00009680 FixItHint Hint;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009681
Chris Lattner5cf216b2008-01-04 18:04:52 +00009682 switch (ConvTy) {
9683 default: assert(0 && "Unknown conversion type");
9684 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009685 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009686 DiagKind = diag::ext_typecheck_convert_pointer_int;
9687 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009688 case IntToPointer:
9689 DiagKind = diag::ext_typecheck_convert_int_pointer;
9690 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009691 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009692 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009693 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9694 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009695 case IncompatiblePointerSign:
9696 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9697 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009698 case FunctionVoidPointer:
9699 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9700 break;
John McCall86c05f32011-02-01 00:10:29 +00009701 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009702 // Perform array-to-pointer decay if necessary.
9703 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9704
John McCall86c05f32011-02-01 00:10:29 +00009705 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9706 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9707 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9708 DiagKind = diag::err_typecheck_incompatible_address_space;
9709 break;
9710 }
9711
9712 llvm_unreachable("unknown error case for discarding qualifiers!");
9713 // fallthrough
9714 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009715 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009716 // If the qualifiers lost were because we were applying the
9717 // (deprecated) C++ conversion from a string literal to a char*
9718 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9719 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009720 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009721 // bit of refactoring (so that the second argument is an
9722 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009723 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009724 // C++ semantics.
9725 if (getLangOptions().CPlusPlus &&
9726 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9727 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009728 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9729 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009730 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009731 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009732 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009733 case IntToBlockPointer:
9734 DiagKind = diag::err_int_to_block_pointer;
9735 break;
9736 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009737 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009738 break;
Steve Naroff39579072008-10-14 22:18:38 +00009739 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009740 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009741 // it can give a more specific diagnostic.
9742 DiagKind = diag::warn_incompatible_qualified_id;
9743 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009744 case IncompatibleVectors:
9745 DiagKind = diag::warn_incompatible_vectors;
9746 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009747 case Incompatible:
9748 DiagKind = diag::err_typecheck_convert_incompatible;
9749 isInvalid = true;
9750 break;
9751 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009752
Douglas Gregord4eea832010-04-09 00:35:39 +00009753 QualType FirstType, SecondType;
9754 switch (Action) {
9755 case AA_Assigning:
9756 case AA_Initializing:
9757 // The destination type comes first.
9758 FirstType = DstType;
9759 SecondType = SrcType;
9760 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009761
Douglas Gregord4eea832010-04-09 00:35:39 +00009762 case AA_Returning:
9763 case AA_Passing:
9764 case AA_Converting:
9765 case AA_Sending:
9766 case AA_Casting:
9767 // The source type comes first.
9768 FirstType = SrcType;
9769 SecondType = DstType;
9770 break;
9771 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009772
Douglas Gregord4eea832010-04-09 00:35:39 +00009773 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009774 << SrcExpr->getSourceRange() << Hint;
Douglas Gregora41a8c52010-04-22 00:20:18 +00009775 if (Complained)
9776 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009777 return isInvalid;
9778}
Anders Carlssone21555e2008-11-30 19:50:32 +00009779
Chris Lattner3bf68932009-04-25 21:59:05 +00009780bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009781 llvm::APSInt ICEResult;
9782 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9783 if (Result)
9784 *Result = ICEResult;
9785 return false;
9786 }
9787
Anders Carlssone21555e2008-11-30 19:50:32 +00009788 Expr::EvalResult EvalResult;
9789
Mike Stumpeed9cac2009-02-19 03:04:26 +00009790 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00009791 EvalResult.HasSideEffects) {
9792 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9793
9794 if (EvalResult.Diag) {
9795 // We only show the note if it's not the usual "invalid subexpression"
9796 // or if it's actually in a subexpression.
9797 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9798 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9799 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9800 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009801
Anders Carlssone21555e2008-11-30 19:50:32 +00009802 return true;
9803 }
9804
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009805 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9806 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00009807
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009808 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009809 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9810 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009811 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009812
Anders Carlssone21555e2008-11-30 19:50:32 +00009813 if (Result)
9814 *Result = EvalResult.Val.getInt();
9815 return false;
9816}
Douglas Gregore0762c92009-06-19 23:52:42 +00009817
Douglas Gregor2afce722009-11-26 00:44:06 +00009818void
Mike Stump1eb44332009-09-09 15:08:12 +00009819Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009820 ExprEvalContexts.push_back(
9821 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00009822}
9823
Mike Stump1eb44332009-09-09 15:08:12 +00009824void
Douglas Gregor2afce722009-11-26 00:44:06 +00009825Sema::PopExpressionEvaluationContext() {
9826 // Pop the current expression evaluation context off the stack.
9827 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9828 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009829
Douglas Gregor06d33692009-12-12 07:57:52 +00009830 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9831 if (Rec.PotentiallyReferenced) {
9832 // Mark any remaining declarations in the current position of the stack
9833 // as "referenced". If they were not meant to be referenced, semantic
9834 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009835 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00009836 I = Rec.PotentiallyReferenced->begin(),
9837 IEnd = Rec.PotentiallyReferenced->end();
9838 I != IEnd; ++I)
9839 MarkDeclarationReferenced(I->first, I->second);
9840 }
9841
9842 if (Rec.PotentiallyDiagnosed) {
9843 // Emit any pending diagnostics.
9844 for (PotentiallyEmittedDiagnostics::iterator
9845 I = Rec.PotentiallyDiagnosed->begin(),
9846 IEnd = Rec.PotentiallyDiagnosed->end();
9847 I != IEnd; ++I)
9848 Diag(I->first, I->second);
9849 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009850 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009851
9852 // When are coming out of an unevaluated context, clear out any
9853 // temporaries that we may have created as part of the evaluation of
9854 // the expression in that context: they aren't relevant because they
9855 // will never be constructed.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009856 if (Rec.Context == Unevaluated &&
Douglas Gregor2afce722009-11-26 00:44:06 +00009857 ExprTemporaries.size() > Rec.NumTemporaries)
9858 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9859 ExprTemporaries.end());
9860
9861 // Destroy the popped expression evaluation record.
9862 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009863}
Douglas Gregore0762c92009-06-19 23:52:42 +00009864
9865/// \brief Note that the given declaration was referenced in the source code.
9866///
9867/// This routine should be invoke whenever a given declaration is referenced
9868/// in the source code, and where that reference occurred. If this declaration
9869/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9870/// C99 6.9p3), then the declaration will be marked as used.
9871///
9872/// \param Loc the location where the declaration was referenced.
9873///
9874/// \param D the declaration that has been referenced by the source code.
9875void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9876 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009877
Douglas Gregorc070cc62010-06-17 23:14:26 +00009878 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009879 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009880
Douglas Gregorb5352cf2009-10-08 21:35:42 +00009881 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9882 // template or not. The reason for this is that unevaluated expressions
9883 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9884 // -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009885 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009886 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009887 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009888 return;
9889 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009890
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009891 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9892 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009893
Douglas Gregore0762c92009-06-19 23:52:42 +00009894 // Do not mark anything as "used" within a dependent context; wait for
9895 // an instantiation.
9896 if (CurContext->isDependentContext())
9897 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009898
Douglas Gregor2afce722009-11-26 00:44:06 +00009899 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009900 case Unevaluated:
9901 // We are in an expression that is not potentially evaluated; do nothing.
9902 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009903
Douglas Gregorac7610d2009-06-22 20:57:11 +00009904 case PotentiallyEvaluated:
9905 // We are in a potentially-evaluated expression, so this declaration is
9906 // "used"; handle this below.
9907 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009908
Douglas Gregorac7610d2009-06-22 20:57:11 +00009909 case PotentiallyPotentiallyEvaluated:
9910 // We are in an expression that may be potentially evaluated; queue this
9911 // declaration reference until we know whether the expression is
9912 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009913 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009914 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009915
9916 case PotentiallyEvaluatedIfUsed:
9917 // Referenced declarations will only be used if the construct in the
9918 // containing expression is used.
9919 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009920 }
Mike Stump1eb44332009-09-09 15:08:12 +00009921
Douglas Gregore0762c92009-06-19 23:52:42 +00009922 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009923 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009924 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00009925 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00009926 if (Constructor->getParent()->hasTrivialConstructor())
9927 return;
9928 if (!Constructor->isUsed(false))
9929 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00009930 } else if (Constructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00009931 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009932 if (!Constructor->isUsed(false))
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009933 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9934 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009935
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009936 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009937 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009938 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009939 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009940 if (Destructor->isVirtual())
9941 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009942 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9943 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9944 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009945 if (!MethodDecl->isUsed(false))
Douglas Gregor39957dc2010-05-01 15:04:51 +00009946 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009947 } else if (MethodDecl->isVirtual())
9948 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009949 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009950 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +00009951 // Recursive functions should be marked when used from another function.
9952 if (CurContext == Function) return;
9953
Mike Stump1eb44332009-09-09 15:08:12 +00009954 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009955 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009956 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009957 bool AlreadyInstantiated = false;
9958 if (FunctionTemplateSpecializationInfo *SpecInfo
9959 = Function->getTemplateSpecializationInfo()) {
9960 if (SpecInfo->getPointOfInstantiation().isInvalid())
9961 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009962 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009963 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009964 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009965 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009966 = Function->getMemberSpecializationInfo()) {
9967 if (MSInfo->getPointOfInstantiation().isInvalid())
9968 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009969 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009970 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009971 AlreadyInstantiated = true;
9972 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009973
Douglas Gregor60406be2010-01-16 22:29:39 +00009974 if (!AlreadyInstantiated) {
9975 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9976 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9977 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9978 Loc));
9979 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00009980 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00009981 }
John McCall15e310a2011-02-19 02:53:41 +00009982 } else {
9983 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +00009984 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9985 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00009986 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00009987 MarkDeclarationReferenced(Loc, *i);
9988 }
John McCall15e310a2011-02-19 02:53:41 +00009989 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009990
John McCall15e310a2011-02-19 02:53:41 +00009991 // Keep track of used but undefined functions.
9992 if (!Function->isPure() && !Function->hasBody() &&
9993 Function->getLinkage() != ExternalLinkage) {
9994 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9995 if (old.isInvalid()) old = Loc;
9996 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00009997
John McCall15e310a2011-02-19 02:53:41 +00009998 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +00009999 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +000010000 }
Mike Stump1eb44332009-09-09 15:08:12 +000010001
Douglas Gregore0762c92009-06-19 23:52:42 +000010002 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +000010003 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +000010004 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010005 Var->getInstantiatedFromStaticDataMember()) {
10006 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10007 assert(MSInfo && "Missing member specialization information?");
10008 if (MSInfo->getPointOfInstantiation().isInvalid() &&
10009 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
10010 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth62c78d52010-08-25 08:44:16 +000010011 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010012 }
10013 }
Mike Stump1eb44332009-09-09 15:08:12 +000010014
John McCall77efc682011-02-21 19:25:48 +000010015 // Keep track of used but undefined variables. We make a hole in
10016 // the warning for static const data members with in-line
10017 // initializers.
John McCall15e310a2011-02-19 02:53:41 +000010018 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall77efc682011-02-21 19:25:48 +000010019 && Var->getLinkage() != ExternalLinkage
10020 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall15e310a2011-02-19 02:53:41 +000010021 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
10022 if (old.isInvalid()) old = Loc;
10023 }
Douglas Gregor7caa6822009-07-24 20:34:43 +000010024
Douglas Gregore0762c92009-06-19 23:52:42 +000010025 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +000010026 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +000010027 }
Douglas Gregore0762c92009-06-19 23:52:42 +000010028}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010029
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010030namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010031 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010032 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010033 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010034 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10035 Sema &S;
10036 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010037
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010038 public:
10039 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010040
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010041 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010042
10043 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10044 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010045 };
10046}
10047
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010048bool MarkReferencedDecls::TraverseTemplateArgument(
10049 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010050 if (Arg.getKind() == TemplateArgument::Declaration) {
10051 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
10052 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010053
10054 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010055}
10056
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010057bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010058 if (ClassTemplateSpecializationDecl *Spec
10059 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10060 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000010061 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010062 }
10063
Chandler Carruthe3e210c2010-06-10 10:31:57 +000010064 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010065}
10066
10067void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10068 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010069 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010070}
10071
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010072namespace {
10073 /// \brief Helper class that marks all of the declarations referenced by
10074 /// potentially-evaluated subexpressions as "referenced".
10075 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10076 Sema &S;
10077
10078 public:
10079 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10080
10081 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
10082
10083 void VisitDeclRefExpr(DeclRefExpr *E) {
10084 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10085 }
10086
10087 void VisitMemberExpr(MemberExpr *E) {
10088 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010089 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010090 }
10091
10092 void VisitCXXNewExpr(CXXNewExpr *E) {
10093 if (E->getConstructor())
10094 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
10095 if (E->getOperatorNew())
10096 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
10097 if (E->getOperatorDelete())
10098 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010099 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010100 }
10101
10102 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10103 if (E->getOperatorDelete())
10104 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000010105 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10106 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10107 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10108 S.MarkDeclarationReferenced(E->getLocStart(),
10109 S.LookupDestructor(Record));
10110 }
10111
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010112 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010113 }
10114
10115 void VisitCXXConstructExpr(CXXConstructExpr *E) {
10116 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010117 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010118 }
10119
10120 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
10121 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10122 }
Douglas Gregor102ff972010-10-19 17:17:35 +000010123
10124 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10125 Visit(E->getExpr());
10126 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010127 };
10128}
10129
10130/// \brief Mark any declarations that appear within this expression or any
10131/// potentially-evaluated subexpressions as "referenced".
10132void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
10133 EvaluatedExprMarker(*this).Visit(E);
10134}
10135
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010136/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10137/// of the program being compiled.
10138///
10139/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010140/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010141/// possibility that the code will actually be executable. Code in sizeof()
10142/// expressions, code used only during overload resolution, etc., are not
10143/// potentially evaluated. This routine will suppress such diagnostics or,
10144/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010145/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010146/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010147///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010148/// This routine should be used for all diagnostics that describe the run-time
10149/// behavior of a program, such as passing a non-POD value through an ellipsis.
10150/// Failure to do so will likely result in spurious diagnostics or failures
10151/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek762696f2011-02-23 01:51:43 +000010152bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010153 const PartialDiagnostic &PD) {
10154 switch (ExprEvalContexts.back().Context ) {
10155 case Unevaluated:
10156 // The argument will never be evaluated, so don't complain.
10157 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010158
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010159 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010160 case PotentiallyEvaluatedIfUsed:
Ted Kremenek351ba912011-02-23 01:52:04 +000010161 if (stmt && getCurFunctionOrMethodDecl()) {
10162 FunctionScopes.back()->PossiblyUnreachableDiags.
10163 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
10164 }
10165 else
10166 Diag(Loc, PD);
10167
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010168 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010169
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010170 case PotentiallyPotentiallyEvaluated:
10171 ExprEvalContexts.back().addDiagnostic(Loc, PD);
10172 break;
10173 }
10174
10175 return false;
10176}
10177
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010178bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10179 CallExpr *CE, FunctionDecl *FD) {
10180 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10181 return false;
10182
10183 PartialDiagnostic Note =
10184 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
10185 << FD->getDeclName() : PDiag();
10186 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010187
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010188 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010189 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010190 PDiag(diag::err_call_function_incomplete_return)
10191 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010192 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010193 << CE->getSourceRange(),
10194 std::make_pair(NoteLoc, Note)))
10195 return true;
10196
10197 return false;
10198}
10199
Douglas Gregor92c3a042011-01-19 16:50:08 +000010200// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000010201// will prevent this condition from triggering, which is what we want.
10202void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10203 SourceLocation Loc;
10204
John McCalla52ef082009-11-11 02:41:58 +000010205 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000010206 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000010207
John McCall5a881bb2009-10-12 21:59:07 +000010208 if (isa<BinaryOperator>(E)) {
10209 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +000010210 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000010211 return;
10212
Douglas Gregor92c3a042011-01-19 16:50:08 +000010213 IsOrAssign = Op->getOpcode() == BO_OrAssign;
10214
John McCallc8d8ac52009-11-12 00:06:05 +000010215 // Greylist some idioms by putting them into a warning subcategory.
10216 if (ObjCMessageExpr *ME
10217 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10218 Selector Sel = ME->getSelector();
10219
John McCallc8d8ac52009-11-12 00:06:05 +000010220 // self = [<foo> init...]
Douglas Gregor813d8342011-02-18 22:29:55 +000010221 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000010222 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10223
10224 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000010225 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000010226 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10227 }
John McCalla52ef082009-11-11 02:41:58 +000010228
John McCall5a881bb2009-10-12 21:59:07 +000010229 Loc = Op->getOperatorLoc();
10230 } else if (isa<CXXOperatorCallExpr>(E)) {
10231 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +000010232 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000010233 return;
10234
Douglas Gregor92c3a042011-01-19 16:50:08 +000010235 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000010236 Loc = Op->getOperatorLoc();
10237 } else {
10238 // Not an assignment.
10239 return;
10240 }
10241
Douglas Gregor55b38842010-04-14 16:09:52 +000010242 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000010243
10244 if (IsOrAssign)
10245 Diag(Loc, diag::note_condition_or_assign_to_comparison)
10246 << FixItHint::CreateReplacement(Loc, "!=");
10247 else
10248 Diag(Loc, diag::note_condition_assign_to_comparison)
10249 << FixItHint::CreateReplacement(Loc, "==");
10250
Fariborz Jahanian81ab3cf2011-04-13 20:31:26 +000010251 SourceLocation Open = E->getSourceRange().getBegin();
Eli Friedmandde55572011-04-14 00:51:41 +000010252 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Fariborz Jahanian60274612011-04-13 22:18:37 +000010253 Diag(Loc, diag::note_condition_assign_silence)
10254 << FixItHint::CreateInsertion(Open, "(")
Eli Friedmandde55572011-04-14 00:51:41 +000010255 << FixItHint::CreateInsertion(Close, ")");
John McCall5a881bb2009-10-12 21:59:07 +000010256}
10257
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010258/// \brief Redundant parentheses over an equality comparison can indicate
10259/// that the user intended an assignment used as condition.
10260void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000010261 // Don't warn if the parens came from a macro.
10262 SourceLocation parenLoc = parenE->getLocStart();
10263 if (parenLoc.isInvalid() || parenLoc.isMacroID())
10264 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000010265 // Don't warn for dependent expressions.
10266 if (parenE->isTypeDependent())
10267 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000010268
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010269 Expr *E = parenE->IgnoreParens();
10270
10271 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000010272 if (opE->getOpcode() == BO_EQ &&
10273 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10274 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010275 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000010276
Ted Kremenekf7275cd2011-02-02 02:20:30 +000010277 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
10278 Diag(Loc, diag::note_equality_comparison_to_assign)
10279 << FixItHint::CreateReplacement(Loc, "=");
10280 Diag(Loc, diag::note_equality_comparison_silence)
10281 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
10282 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010283 }
10284}
10285
John Wiegley429bb272011-04-08 18:41:53 +000010286ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000010287 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010288 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10289 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000010290
10291 if (!E->isTypeDependent()) {
John Wiegley429bb272011-04-08 18:41:53 +000010292 if (E->isBoundMemberFunction(Context)) {
10293 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000010294 << E->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +000010295 return ExprError();
10296 }
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000010297
John McCallf6a16482010-12-04 03:47:34 +000010298 if (getLangOptions().CPlusPlus)
10299 return CheckCXXBooleanCondition(E); // C++ 6.4p4
10300
John Wiegley429bb272011-04-08 18:41:53 +000010301 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10302 if (ERes.isInvalid())
10303 return ExprError();
10304 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000010305
10306 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000010307 if (!T->isScalarType()) { // C99 6.8.4.1p1
10308 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10309 << T << E->getSourceRange();
10310 return ExprError();
10311 }
John McCall5a881bb2009-10-12 21:59:07 +000010312 }
10313
John Wiegley429bb272011-04-08 18:41:53 +000010314 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000010315}
Douglas Gregor586596f2010-05-06 17:25:47 +000010316
John McCall60d7b3a2010-08-24 06:29:42 +000010317ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
10318 Expr *Sub) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +000010319 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +000010320 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010321
10322 return CheckBooleanCondition(Sub, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000010323}
John McCall2a984ca2010-10-12 00:20:44 +000010324
John McCall1de4d4e2011-04-07 08:22:57 +000010325namespace {
John McCall755d8492011-04-12 00:42:48 +000010326 /// A visitor for rebuilding a call to an __unknown_any expression
10327 /// to have an appropriate type.
10328 struct RebuildUnknownAnyFunction
10329 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10330
10331 Sema &S;
10332
10333 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10334
10335 ExprResult VisitStmt(Stmt *S) {
10336 llvm_unreachable("unexpected statement!");
10337 return ExprError();
10338 }
10339
10340 ExprResult VisitExpr(Expr *expr) {
10341 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
10342 << expr->getSourceRange();
10343 return ExprError();
10344 }
10345
10346 /// Rebuild an expression which simply semantically wraps another
10347 /// expression which it shares the type and value kind of.
10348 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10349 ExprResult subResult = Visit(expr->getSubExpr());
10350 if (subResult.isInvalid()) return ExprError();
10351
10352 Expr *subExpr = subResult.take();
10353 expr->setSubExpr(subExpr);
10354 expr->setType(subExpr->getType());
10355 expr->setValueKind(subExpr->getValueKind());
10356 assert(expr->getObjectKind() == OK_Ordinary);
10357 return expr;
10358 }
10359
10360 ExprResult VisitParenExpr(ParenExpr *paren) {
10361 return rebuildSugarExpr(paren);
10362 }
10363
10364 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10365 return rebuildSugarExpr(op);
10366 }
10367
10368 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10369 ExprResult subResult = Visit(op->getSubExpr());
10370 if (subResult.isInvalid()) return ExprError();
10371
10372 Expr *subExpr = subResult.take();
10373 op->setSubExpr(subExpr);
10374 op->setType(S.Context.getPointerType(subExpr->getType()));
10375 assert(op->getValueKind() == VK_RValue);
10376 assert(op->getObjectKind() == OK_Ordinary);
10377 return op;
10378 }
10379
10380 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
10381 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
10382
10383 expr->setType(decl->getType());
10384
10385 assert(expr->getValueKind() == VK_RValue);
10386 if (S.getLangOptions().CPlusPlus &&
10387 !(isa<CXXMethodDecl>(decl) &&
10388 cast<CXXMethodDecl>(decl)->isInstance()))
10389 expr->setValueKind(VK_LValue);
10390
10391 return expr;
10392 }
10393
10394 ExprResult VisitMemberExpr(MemberExpr *mem) {
10395 return resolveDecl(mem, mem->getMemberDecl());
10396 }
10397
10398 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
10399 return resolveDecl(ref, ref->getDecl());
10400 }
10401 };
10402}
10403
10404/// Given a function expression of unknown-any type, try to rebuild it
10405/// to have a function type.
10406static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
10407 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
10408 if (result.isInvalid()) return ExprError();
10409 return S.DefaultFunctionArrayConversion(result.take());
10410}
10411
10412namespace {
John McCall379b5152011-04-11 07:02:50 +000010413 /// A visitor for rebuilding an expression of type __unknown_anytype
10414 /// into one which resolves the type directly on the referring
10415 /// expression. Strict preservation of the original source
10416 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000010417 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000010418 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000010419
10420 Sema &S;
10421
10422 /// The current destination type.
10423 QualType DestType;
10424
10425 RebuildUnknownAnyExpr(Sema &S, QualType castType)
10426 : S(S), DestType(castType) {}
10427
John McCalla5fc4722011-04-09 22:50:59 +000010428 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000010429 llvm_unreachable("unexpected statement!");
John McCalla5fc4722011-04-09 22:50:59 +000010430 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010431 }
10432
John McCall379b5152011-04-11 07:02:50 +000010433 ExprResult VisitExpr(Expr *expr) {
10434 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10435 << expr->getSourceRange();
10436 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010437 }
10438
John McCall379b5152011-04-11 07:02:50 +000010439 ExprResult VisitCallExpr(CallExpr *call);
10440 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
10441
John McCalla5fc4722011-04-09 22:50:59 +000010442 /// Rebuild an expression which simply semantically wraps another
10443 /// expression which it shares the type and value kind of.
10444 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10445 ExprResult subResult = Visit(expr->getSubExpr());
John McCall755d8492011-04-12 00:42:48 +000010446 if (subResult.isInvalid()) return ExprError();
John McCalla5fc4722011-04-09 22:50:59 +000010447 Expr *subExpr = subResult.take();
10448 expr->setSubExpr(subExpr);
10449 expr->setType(subExpr->getType());
10450 expr->setValueKind(subExpr->getValueKind());
10451 assert(expr->getObjectKind() == OK_Ordinary);
10452 return expr;
10453 }
John McCall1de4d4e2011-04-07 08:22:57 +000010454
John McCalla5fc4722011-04-09 22:50:59 +000010455 ExprResult VisitParenExpr(ParenExpr *paren) {
10456 return rebuildSugarExpr(paren);
10457 }
10458
10459 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10460 return rebuildSugarExpr(op);
10461 }
10462
John McCall755d8492011-04-12 00:42:48 +000010463 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10464 const PointerType *ptr = DestType->getAs<PointerType>();
10465 if (!ptr) {
10466 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
10467 << op->getSourceRange();
10468 return ExprError();
10469 }
10470 assert(op->getValueKind() == VK_RValue);
10471 assert(op->getObjectKind() == OK_Ordinary);
10472 op->setType(DestType);
10473
10474 // Build the sub-expression as if it were an object of the pointee type.
10475 DestType = ptr->getPointeeType();
10476 ExprResult subResult = Visit(op->getSubExpr());
10477 if (subResult.isInvalid()) return ExprError();
10478 op->setSubExpr(subResult.take());
10479 return op;
10480 }
10481
John McCall379b5152011-04-11 07:02:50 +000010482 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCalla5fc4722011-04-09 22:50:59 +000010483
John McCall755d8492011-04-12 00:42:48 +000010484 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCalla5fc4722011-04-09 22:50:59 +000010485
John McCall755d8492011-04-12 00:42:48 +000010486 ExprResult VisitMemberExpr(MemberExpr *mem) {
10487 return resolveDecl(mem, mem->getMemberDecl());
10488 }
John McCalla5fc4722011-04-09 22:50:59 +000010489
10490 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall379b5152011-04-11 07:02:50 +000010491 return resolveDecl(ref, ref->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000010492 }
10493 };
10494}
10495
John McCall379b5152011-04-11 07:02:50 +000010496/// Rebuilds a call expression which yielded __unknown_anytype.
10497ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
10498 Expr *callee = call->getCallee();
10499
10500 enum FnKind {
10501 FK_Function,
10502 FK_FunctionPointer,
10503 FK_BlockPointer
10504 };
10505
10506 FnKind kind;
10507 QualType type = callee->getType();
10508 if (type->isFunctionType()) {
10509 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
10510 kind = FK_Function;
10511 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
10512 type = ptr->getPointeeType();
10513 kind = FK_FunctionPointer;
10514 } else {
10515 type = type->castAs<BlockPointerType>()->getPointeeType();
10516 kind = FK_BlockPointer;
10517 }
10518 const FunctionType *fnType = type->castAs<FunctionType>();
10519
10520 // Verify that this is a legal result type of a function.
10521 if (DestType->isArrayType() || DestType->isFunctionType()) {
10522 unsigned diagID = diag::err_func_returning_array_function;
10523 if (kind == FK_BlockPointer)
10524 diagID = diag::err_block_returning_array_function;
10525
10526 S.Diag(call->getExprLoc(), diagID)
10527 << DestType->isFunctionType() << DestType;
10528 return ExprError();
10529 }
10530
10531 // Otherwise, go ahead and set DestType as the call's result.
10532 call->setType(DestType.getNonLValueExprType(S.Context));
10533 call->setValueKind(Expr::getValueKindForType(DestType));
10534 assert(call->getObjectKind() == OK_Ordinary);
10535
10536 // Rebuild the function type, replacing the result type with DestType.
10537 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
10538 DestType = S.Context.getFunctionType(DestType,
10539 proto->arg_type_begin(),
10540 proto->getNumArgs(),
10541 proto->getExtProtoInfo());
10542 else
10543 DestType = S.Context.getFunctionNoProtoType(DestType,
10544 fnType->getExtInfo());
10545
10546 // Rebuild the appropriate pointer-to-function type.
10547 switch (kind) {
10548 case FK_Function:
10549 // Nothing to do.
10550 break;
10551
10552 case FK_FunctionPointer:
10553 DestType = S.Context.getPointerType(DestType);
10554 break;
10555
10556 case FK_BlockPointer:
10557 DestType = S.Context.getBlockPointerType(DestType);
10558 break;
10559 }
10560
10561 // Finally, we can recurse.
10562 ExprResult calleeResult = Visit(callee);
10563 if (!calleeResult.isUsable()) return ExprError();
10564 call->setCallee(calleeResult.take());
10565
10566 // Bind a temporary if necessary.
10567 return S.MaybeBindToTemporary(call);
10568}
10569
10570ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall755d8492011-04-12 00:42:48 +000010571 ObjCMethodDecl *method = msg->getMethodDecl();
10572 assert(method && "__unknown_anytype message without result type?");
John McCall379b5152011-04-11 07:02:50 +000010573
John McCall755d8492011-04-12 00:42:48 +000010574 // Verify that this is a legal result type of a call.
10575 if (DestType->isArrayType() || DestType->isFunctionType()) {
10576 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
10577 << DestType->isFunctionType() << DestType;
10578 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010579 }
10580
John McCall755d8492011-04-12 00:42:48 +000010581 assert(method->getResultType() == S.Context.UnknownAnyTy);
10582 method->setResultType(DestType);
10583
John McCall379b5152011-04-11 07:02:50 +000010584 // Change the type of the message.
John McCall755d8492011-04-12 00:42:48 +000010585 msg->setType(DestType.getNonReferenceType());
10586 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000010587
John McCall755d8492011-04-12 00:42:48 +000010588 return S.MaybeBindToTemporary(msg);
John McCall379b5152011-04-11 07:02:50 +000010589}
10590
10591ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall755d8492011-04-12 00:42:48 +000010592 // The only case we should ever see here is a function-to-pointer decay.
John McCall379b5152011-04-11 07:02:50 +000010593 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall379b5152011-04-11 07:02:50 +000010594 assert(ice->getValueKind() == VK_RValue);
10595 assert(ice->getObjectKind() == OK_Ordinary);
10596
John McCall755d8492011-04-12 00:42:48 +000010597 ice->setType(DestType);
10598
John McCall379b5152011-04-11 07:02:50 +000010599 // Rebuild the sub-expression as the pointee (function) type.
10600 DestType = DestType->castAs<PointerType>()->getPointeeType();
10601
10602 ExprResult result = Visit(ice->getSubExpr());
10603 if (!result.isUsable()) return ExprError();
10604
10605 ice->setSubExpr(result.take());
10606 return S.Owned(ice);
10607}
10608
John McCall755d8492011-04-12 00:42:48 +000010609ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall379b5152011-04-11 07:02:50 +000010610 ExprValueKind valueKind = VK_LValue;
John McCall379b5152011-04-11 07:02:50 +000010611 QualType type = DestType;
10612
10613 // We know how to make this work for certain kinds of decls:
10614
10615 // - functions
John McCall755d8492011-04-12 00:42:48 +000010616 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
10617 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
John McCall379b5152011-04-11 07:02:50 +000010618 if (method->isInstance()) valueKind = VK_RValue;
10619
10620 // This is true because FunctionDecls must always have function
10621 // type, so we can't be resolving the entire thing at once.
10622 assert(type->isFunctionType());
10623
10624 // Function references aren't l-values in C.
10625 if (!S.getLangOptions().CPlusPlus)
10626 valueKind = VK_RValue;
10627
10628 // - variables
10629 } else if (isa<VarDecl>(decl)) {
John McCall755d8492011-04-12 00:42:48 +000010630 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
10631 type = refTy->getPointeeType();
John McCall379b5152011-04-11 07:02:50 +000010632 } else if (type->isFunctionType()) {
John McCall755d8492011-04-12 00:42:48 +000010633 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
10634 << decl << expr->getSourceRange();
10635 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010636 }
10637
10638 // - nothing else
10639 } else {
10640 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10641 << decl << expr->getSourceRange();
10642 return ExprError();
10643 }
10644
John McCall755d8492011-04-12 00:42:48 +000010645 decl->setType(DestType);
10646 expr->setType(type);
10647 expr->setValueKind(valueKind);
10648 return S.Owned(expr);
John McCall379b5152011-04-11 07:02:50 +000010649}
10650
John McCall1de4d4e2011-04-07 08:22:57 +000010651/// Check a cast of an unknown-any type. We intentionally only
10652/// trigger this for C-style casts.
John Wiegley429bb272011-04-08 18:41:53 +000010653ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
10654 Expr *castExpr, CastKind &castKind,
10655 ExprValueKind &VK, CXXCastPath &path) {
John McCall1de4d4e2011-04-07 08:22:57 +000010656 // Rewrite the casted expression from scratch.
John McCalla5fc4722011-04-09 22:50:59 +000010657 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
10658 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010659
John McCalla5fc4722011-04-09 22:50:59 +000010660 castExpr = result.take();
10661 VK = castExpr->getValueKind();
10662 castKind = CK_NoOp;
10663
10664 return castExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000010665}
10666
10667static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
10668 Expr *orig = e;
John McCall379b5152011-04-11 07:02:50 +000010669 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000010670 while (true) {
10671 e = e->IgnoreParenImpCasts();
John McCall379b5152011-04-11 07:02:50 +000010672 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall1de4d4e2011-04-07 08:22:57 +000010673 e = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000010674 diagID = diag::err_uncasted_call_of_unknown_any;
10675 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000010676 break;
John McCall379b5152011-04-11 07:02:50 +000010677 }
John McCall1de4d4e2011-04-07 08:22:57 +000010678 }
10679
John McCall379b5152011-04-11 07:02:50 +000010680 SourceLocation loc;
10681 NamedDecl *d;
10682 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10683 loc = ref->getLocation();
10684 d = ref->getDecl();
10685 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
10686 loc = mem->getMemberLoc();
10687 d = mem->getMemberDecl();
10688 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
10689 diagID = diag::err_uncasted_call_of_unknown_any;
10690 loc = msg->getSelectorLoc();
10691 d = msg->getMethodDecl();
10692 assert(d && "unknown method returning __unknown_any?");
10693 } else {
10694 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10695 << e->getSourceRange();
10696 return ExprError();
10697 }
10698
10699 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000010700
10701 // Never recoverable.
10702 return ExprError();
10703}
10704
John McCall2a984ca2010-10-12 00:20:44 +000010705/// Check for operands with placeholder types and complain if found.
10706/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000010707ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall1de4d4e2011-04-07 08:22:57 +000010708 // Placeholder types are always *exactly* the appropriate builtin type.
10709 QualType type = E->getType();
John McCall2a984ca2010-10-12 00:20:44 +000010710
John McCall1de4d4e2011-04-07 08:22:57 +000010711 // Overloaded expressions.
10712 if (type == Context.OverloadTy)
10713 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregordb2eae62011-03-16 19:16:25 +000010714 E->getSourceRange(),
John McCall1de4d4e2011-04-07 08:22:57 +000010715 QualType(),
10716 diag::err_ovl_unresolvable);
10717
10718 // Expressions of unknown type.
10719 if (type == Context.UnknownAnyTy)
10720 return diagnoseUnknownAnyExpr(*this, E);
10721
10722 assert(!type->isPlaceholderType());
10723 return Owned(E);
John McCall2a984ca2010-10-12 00:20:44 +000010724}