blob: 8ccb9b8180443590aee4f750b42dc31ea12e8c25 [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 Lattnere7a2e912008-07-25 21:10:04 +0000351/// sometimes surpressed. For example, the array->pointer conversion doesn't
352/// 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
Steve Narofff69936d2007-09-16 03:34:24 +0000751/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000752/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
753/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
754/// multiple tokens. However, the common case is that StringToks points to one
755/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000756///
John McCall60d7b3a2010-08-24 06:29:42 +0000757ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +0000758Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000759 assert(NumStringToks && "Must have at least one string!");
760
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000761 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000762 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000763 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000764
765 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
766 for (unsigned i = 0; i != NumStringToks; ++i)
767 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000768
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000769 QualType StrTy = Context.CharTy;
Anders Carlsson96b4adc2011-04-06 18:42:48 +0000770 if (Literal.AnyWide)
771 StrTy = Context.getWCharType();
772 else if (Literal.Pascal)
773 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000774
775 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +0000776 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +0000777 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000778
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000779 // Get an array type for the string, according to C99 6.4.5. This includes
780 // the nul terminator character as well as the string length for pascal
781 // strings.
782 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000783 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000784 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +0000787 return Owned(StringLiteral::Create(Context, Literal.GetString(),
788 Literal.GetStringLength(),
Anders Carlsson3e2193c2011-04-14 00:40:03 +0000789 Literal.AnyWide, Literal.Pascal, StrTy,
Sean Hunt6cf75022010-08-30 17:47:05 +0000790 &StringTokLocs[0],
791 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000792}
793
John McCall469a1eb2011-02-02 13:00:07 +0000794enum CaptureResult {
795 /// No capture is required.
796 CR_NoCapture,
797
798 /// A capture is required.
799 CR_Capture,
800
John McCall6b5a61b2011-02-07 10:33:21 +0000801 /// A by-ref capture is required.
802 CR_CaptureByRef,
803
John McCall469a1eb2011-02-02 13:00:07 +0000804 /// An error occurred when trying to capture the given variable.
805 CR_Error
806};
807
808/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +0000809///
John McCall469a1eb2011-02-02 13:00:07 +0000810/// \param var - the variable referenced
811/// \param DC - the context which we couldn't capture through
812static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +0000813diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +0000814 VarDecl *var, DeclContext *DC) {
815 switch (S.ExprEvalContexts.back().Context) {
816 case Sema::Unevaluated:
817 // The argument will never be evaluated, so don't complain.
818 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +0000819
John McCall469a1eb2011-02-02 13:00:07 +0000820 case Sema::PotentiallyEvaluated:
821 case Sema::PotentiallyEvaluatedIfUsed:
822 break;
Chris Lattner639e2d32008-10-20 05:16:36 +0000823
John McCall469a1eb2011-02-02 13:00:07 +0000824 case Sema::PotentiallyPotentiallyEvaluated:
825 // FIXME: delay these!
826 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000827 }
Mike Stump1eb44332009-09-09 15:08:12 +0000828
John McCall469a1eb2011-02-02 13:00:07 +0000829 // Don't diagnose about capture if we're not actually in code right
830 // now; in general, there are more appropriate places that will
831 // diagnose this.
832 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
833
John McCall4f38f412011-03-22 23:15:50 +0000834 // Certain madnesses can happen with parameter declarations, which
835 // we want to ignore.
836 if (isa<ParmVarDecl>(var)) {
837 // - If the parameter still belongs to the translation unit, then
838 // we're actually just using one parameter in the declaration of
839 // the next. This is useful in e.g. VLAs.
840 if (isa<TranslationUnitDecl>(var->getDeclContext()))
841 return CR_NoCapture;
842
843 // - This particular madness can happen in ill-formed default
844 // arguments; claim it's okay and let downstream code handle it.
845 if (S.CurContext == var->getDeclContext()->getParent())
846 return CR_NoCapture;
847 }
John McCall469a1eb2011-02-02 13:00:07 +0000848
849 DeclarationName functionName;
850 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
851 functionName = fn->getDeclName();
852 // FIXME: variable from enclosing block that we couldn't capture from!
853
854 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
855 << var->getIdentifier() << functionName;
856 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
857 << var->getIdentifier();
858
859 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +0000860}
861
John McCall6b5a61b2011-02-07 10:33:21 +0000862/// There is a well-formed capture at a particular scope level;
863/// propagate it through all the nested blocks.
864static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
865 const BlockDecl::Capture &capture) {
866 VarDecl *var = capture.getVariable();
867
868 // Update all the inner blocks with the capture information.
869 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
870 i != e; ++i) {
871 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
872 innerBlock->Captures.push_back(
873 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
874 /*nested*/ true, capture.getCopyExpr()));
875 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
876 }
877
878 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
879}
880
881/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +0000882/// given value in the current context requires a variable capture.
883///
884/// This also keeps the captures set in the BlockScopeInfo records
885/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +0000886static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +0000887 ValueDecl *value) {
888 // Only variables ever require capture.
889 VarDecl *var = dyn_cast<VarDecl>(value);
John McCall76a40212011-02-09 01:13:10 +0000890 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +0000891
892 // Fast path: variables from the current context never require capture.
893 DeclContext *DC = S.CurContext;
894 if (var->getDeclContext() == DC) return CR_NoCapture;
895
896 // Only variables with local storage require capture.
897 // FIXME: What about 'const' variables in C++?
898 if (!var->hasLocalStorage()) return CR_NoCapture;
899
900 // Otherwise, we need to capture.
901
902 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +0000903 do {
904 // Only blocks (and eventually C++0x closures) can capture; other
905 // scopes don't work.
906 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +0000907 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +0000908
909 BlockScopeInfo *blockScope =
910 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
911 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
912
John McCall6b5a61b2011-02-07 10:33:21 +0000913 // Check whether we've already captured it in this block. If so,
914 // we're done.
915 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
916 return propagateCapture(S, functionScopesIndex,
917 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +0000918
919 functionScopesIndex--;
920 DC = cast<BlockDecl>(DC)->getDeclContext();
921 } while (var->getDeclContext() != DC);
922
John McCall6b5a61b2011-02-07 10:33:21 +0000923 // Okay, we descended all the way to the block that defines the variable.
924 // Actually try to capture it.
925 QualType type = var->getType();
926
927 // Prohibit variably-modified types.
928 if (type->isVariablyModifiedType()) {
929 S.Diag(loc, diag::err_ref_vm_type);
930 S.Diag(var->getLocation(), diag::note_declared_at);
931 return CR_Error;
932 }
933
934 // Prohibit arrays, even in __block variables, but not references to
935 // them.
936 if (type->isArrayType()) {
937 S.Diag(loc, diag::err_ref_array_type);
938 S.Diag(var->getLocation(), diag::note_declared_at);
939 return CR_Error;
940 }
941
942 S.MarkDeclarationReferenced(loc, var);
943
944 // The BlocksAttr indicates the variable is bound by-reference.
945 bool byRef = var->hasAttr<BlocksAttr>();
946
947 // Build a copy expression.
948 Expr *copyExpr = 0;
949 if (!byRef && S.getLangOptions().CPlusPlus &&
950 !type->isDependentType() && type->isStructureOrClassType()) {
951 // According to the blocks spec, the capture of a variable from
952 // the stack requires a const copy constructor. This is not true
953 // of the copy/move done to move a __block variable to the heap.
954 type.addConst();
955
956 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
957 ExprResult result =
958 S.PerformCopyInitialization(
959 InitializedEntity::InitializeBlock(var->getLocation(),
960 type, false),
961 loc, S.Owned(declRef));
962
963 // Build a full-expression copy expression if initialization
964 // succeeded and used a non-trivial constructor. Recover from
965 // errors by pretending that the copy isn't necessary.
966 if (!result.isInvalid() &&
967 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
968 result = S.MaybeCreateExprWithCleanups(result);
969 copyExpr = result.take();
970 }
971 }
972
973 // We're currently at the declarer; go back to the closure.
974 functionScopesIndex++;
975 BlockScopeInfo *blockScope =
976 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
977
978 // Build a valid capture in this scope.
979 blockScope->Captures.push_back(
980 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
981 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
982
983 // Propagate that to inner captures if necessary.
984 return propagateCapture(S, functionScopesIndex,
985 blockScope->Captures.back());
986}
987
988static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
989 const DeclarationNameInfo &NameInfo,
990 bool byRef) {
991 assert(isa<VarDecl>(vd) && "capturing non-variable");
992
993 VarDecl *var = cast<VarDecl>(vd);
994 assert(var->hasLocalStorage() && "capturing non-local");
995 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
996
997 QualType exprType = var->getType().getNonReferenceType();
998
999 BlockDeclRefExpr *BDRE;
1000 if (!byRef) {
1001 // The variable will be bound by copy; make it const within the
1002 // closure, but record that this was done in the expression.
1003 bool constAdded = !exprType.isConstQualified();
1004 exprType.addConst();
1005
1006 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1007 NameInfo.getLoc(), false,
1008 constAdded);
1009 } else {
1010 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1011 NameInfo.getLoc(), true);
1012 }
1013
1014 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +00001015}
Chris Lattner639e2d32008-10-20 05:16:36 +00001016
John McCall60d7b3a2010-08-24 06:29:42 +00001017ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001018Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001019 SourceLocation Loc,
1020 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001021 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001022 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001023}
1024
John McCall76a40212011-02-09 01:13:10 +00001025/// BuildDeclRefExpr - Build an expression that references a
1026/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001027ExprResult
John McCall76a40212011-02-09 01:13:10 +00001028Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001029 const DeclarationNameInfo &NameInfo,
1030 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001031 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +00001032
John McCall7eb0a9e2010-11-24 05:12:34 +00001033 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00001034 SS? SS->getWithLocInContext(Context)
1035 : NestedNameSpecifierLoc(),
John McCall7eb0a9e2010-11-24 05:12:34 +00001036 D, NameInfo, Ty, VK);
1037
1038 // Just in case we're building an illegal pointer-to-member.
1039 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1040 E->setObjectKind(OK_BitField);
1041
1042 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001043}
1044
John McCalldfa1edb2010-11-23 20:48:44 +00001045static ExprResult
1046BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1047 const CXXScopeSpec &SS, FieldDecl *Field,
1048 DeclAccessPair FoundDecl,
1049 const DeclarationNameInfo &MemberNameInfo);
1050
John McCall60d7b3a2010-08-24 06:29:42 +00001051ExprResult
John McCall5808ce42011-02-03 08:15:49 +00001052Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1053 SourceLocation loc,
1054 IndirectFieldDecl *indirectField,
1055 Expr *baseObjectExpr,
1056 SourceLocation opLoc) {
1057 // First, build the expression that refers to the base object.
1058
1059 bool baseObjectIsPointer = false;
1060 Qualifiers baseQuals;
1061
1062 // Case 1: the base of the indirect field is not a field.
1063 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregorf5848322011-02-18 02:44:58 +00001064 CXXScopeSpec EmptySS;
John McCall5808ce42011-02-03 08:15:49 +00001065 if (baseVariable) {
1066 assert(baseVariable->getType()->isRecordType());
1067
1068 // In principle we could have a member access expression that
1069 // accesses an anonymous struct/union that's a static member of
1070 // the base object's class. However, under the current standard,
1071 // static data members cannot be anonymous structs or unions.
1072 // Supporting this is as easy as building a MemberExpr here.
1073 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1074
1075 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1076
1077 ExprResult result =
Douglas Gregorf5848322011-02-18 02:44:58 +00001078 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCall5808ce42011-02-03 08:15:49 +00001079 if (result.isInvalid()) return ExprError();
1080
1081 baseObjectExpr = result.take();
1082 baseObjectIsPointer = false;
1083 baseQuals = baseObjectExpr->getType().getQualifiers();
1084
1085 // Case 2: the base of the indirect field is a field and the user
1086 // wrote a member expression.
1087 } else if (baseObjectExpr) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001088 // The caller provided the base object expression. Determine
1089 // whether its a pointer and whether it adds any qualifiers to the
1090 // anonymous struct/union fields we're looking into.
John McCall5808ce42011-02-03 08:15:49 +00001091 QualType objectType = baseObjectExpr->getType();
1092
1093 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1094 baseObjectIsPointer = true;
1095 objectType = ptr->getPointeeType();
1096 } else {
1097 baseObjectIsPointer = false;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001098 }
John McCall5808ce42011-02-03 08:15:49 +00001099 baseQuals = objectType.getQualifiers();
1100
1101 // Case 3: the base of the indirect field is a field and we should
1102 // build an implicit member access.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001103 } else {
1104 // We've found a member of an anonymous struct/union that is
1105 // inside a non-anonymous struct/union, so in a well-formed
1106 // program our base object expression is "this".
John McCall5808ce42011-02-03 08:15:49 +00001107 CXXMethodDecl *method = tryCaptureCXXThis();
1108 if (!method) {
1109 Diag(loc, diag::err_invalid_member_use_in_static_method)
1110 << indirectField->getDeclName();
1111 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001112 }
1113
John McCall5808ce42011-02-03 08:15:49 +00001114 // Our base object expression is "this".
1115 baseObjectExpr =
1116 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1117 /*isImplicit=*/ true);
1118 baseObjectIsPointer = true;
1119 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001120 }
1121
1122 // Build the implicit member references to the field of the
1123 // anonymous struct/union.
John McCall5808ce42011-02-03 08:15:49 +00001124 Expr *result = baseObjectExpr;
1125 IndirectFieldDecl::chain_iterator
1126 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCalldfa1edb2010-11-23 20:48:44 +00001127
John McCall5808ce42011-02-03 08:15:49 +00001128 // Build the first member access in the chain with full information.
1129 if (!baseVariable) {
1130 FieldDecl *field = cast<FieldDecl>(*FI);
John McCalldfa1edb2010-11-23 20:48:44 +00001131
John McCall5808ce42011-02-03 08:15:49 +00001132 // FIXME: use the real found-decl info!
1133 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall0953e762009-09-24 19:53:00 +00001134
John McCall5808ce42011-02-03 08:15:49 +00001135 // Make a nameInfo that properly uses the anonymous name.
1136 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall0953e762009-09-24 19:53:00 +00001137
John McCall5808ce42011-02-03 08:15:49 +00001138 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregorf5848322011-02-18 02:44:58 +00001139 EmptySS, field, foundDecl,
John McCall5808ce42011-02-03 08:15:49 +00001140 memberNameInfo).take();
1141 baseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +00001142
John McCall5808ce42011-02-03 08:15:49 +00001143 // FIXME: check qualified member access
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001144 }
1145
John McCall5808ce42011-02-03 08:15:49 +00001146 // In all cases, we should now skip the first declaration in the chain.
1147 ++FI;
1148
Douglas Gregorf5848322011-02-18 02:44:58 +00001149 while (FI != FEnd) {
1150 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCall5808ce42011-02-03 08:15:49 +00001151
1152 // FIXME: these are somewhat meaningless
1153 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1154 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall5808ce42011-02-03 08:15:49 +00001155
1156 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregorf5848322011-02-18 02:44:58 +00001157 (FI == FEnd? SS : EmptySS), field,
1158 foundDecl, memberNameInfo)
John McCall5808ce42011-02-03 08:15:49 +00001159 .take();
1160 }
1161
1162 return Owned(result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001163}
1164
Abramo Bagnara25777432010-08-11 22:01:17 +00001165/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001166/// possibly a list of template arguments.
1167///
1168/// If this produces template arguments, it is permitted to call
1169/// DecomposeTemplateName.
1170///
1171/// This actually loses a lot of source location information for
1172/// non-standard name kinds; we should consider preserving that in
1173/// some way.
1174static void DecomposeUnqualifiedId(Sema &SemaRef,
1175 const UnqualifiedId &Id,
1176 TemplateArgumentListInfo &Buffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00001177 DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00001178 const TemplateArgumentListInfo *&TemplateArgs) {
1179 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1180 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1181 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1182
1183 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1184 Id.TemplateId->getTemplateArgs(),
1185 Id.TemplateId->NumArgs);
1186 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1187 TemplateArgsPtr.release();
1188
John McCall2b5289b2010-08-23 07:28:44 +00001189 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001190 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1191 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001192 TemplateArgs = &Buffer;
1193 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001194 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001195 TemplateArgs = 0;
1196 }
1197}
1198
John McCallaa81e162009-12-01 22:10:20 +00001199/// Determines if the given class is provably not derived from all of
1200/// the prospective base classes.
1201static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1202 CXXRecordDecl *Record,
1203 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +00001204 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +00001205 return false;
1206
Douglas Gregor952b0172010-02-11 01:04:33 +00001207 RecordDecl *RD = Record->getDefinition();
John McCallb1b42562009-12-01 22:28:41 +00001208 if (!RD) return false;
1209 Record = cast<CXXRecordDecl>(RD);
1210
John McCallaa81e162009-12-01 22:10:20 +00001211 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1212 E = Record->bases_end(); I != E; ++I) {
1213 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1214 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1215 if (!BaseRT) return false;
1216
1217 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +00001218 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1219 return false;
1220 }
1221
1222 return true;
1223}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001224
John McCallaa81e162009-12-01 22:10:20 +00001225enum IMAKind {
1226 /// The reference is definitely not an instance member access.
1227 IMA_Static,
1228
1229 /// The reference may be an implicit instance member access.
1230 IMA_Mixed,
1231
1232 /// The reference may be to an instance member, but it is invalid if
1233 /// so, because the context is not an instance method.
1234 IMA_Mixed_StaticContext,
1235
1236 /// The reference may be to an instance member, but it is invalid if
1237 /// so, because the context is from an unrelated class.
1238 IMA_Mixed_Unrelated,
1239
1240 /// The reference is definitely an implicit instance member access.
1241 IMA_Instance,
1242
1243 /// The reference may be to an unresolved using declaration.
1244 IMA_Unresolved,
1245
1246 /// The reference may be to an unresolved using declaration and the
1247 /// context is not an instance method.
1248 IMA_Unresolved_StaticContext,
1249
John McCallaa81e162009-12-01 22:10:20 +00001250 /// All possible referrents are instance members and the current
1251 /// context is not an instance method.
1252 IMA_Error_StaticContext,
1253
1254 /// All possible referrents are instance members of an unrelated
1255 /// class.
1256 IMA_Error_Unrelated
1257};
1258
1259/// The given lookup names class member(s) and is not being used for
1260/// an address-of-member expression. Classify the type of access
1261/// according to whether it's possible that this reference names an
1262/// instance member. This is best-effort; it is okay to
1263/// conservatively answer "yes", in which case some errors will simply
1264/// not be caught until template-instantiation.
1265static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1266 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +00001267 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +00001268
John McCallea1471e2010-05-20 01:18:31 +00001269 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCallaa81e162009-12-01 22:10:20 +00001270 bool isStaticContext =
John McCallea1471e2010-05-20 01:18:31 +00001271 (!isa<CXXMethodDecl>(DC) ||
1272 cast<CXXMethodDecl>(DC)->isStatic());
John McCallaa81e162009-12-01 22:10:20 +00001273
1274 if (R.isUnresolvableResult())
1275 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1276
1277 // Collect all the declaring classes of instance members we find.
1278 bool hasNonInstance = false;
Sebastian Redlf9780002010-11-26 16:28:07 +00001279 bool hasField = false;
John McCallaa81e162009-12-01 22:10:20 +00001280 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1281 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall161755a2010-04-06 21:38:20 +00001282 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00001283
John McCall161755a2010-04-06 21:38:20 +00001284 if (D->isCXXInstanceMember()) {
Sebastian Redlf9780002010-11-26 16:28:07 +00001285 if (dyn_cast<FieldDecl>(D))
1286 hasField = true;
1287
John McCallaa81e162009-12-01 22:10:20 +00001288 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCallaa81e162009-12-01 22:10:20 +00001289 Classes.insert(R->getCanonicalDecl());
1290 }
1291 else
1292 hasNonInstance = true;
1293 }
1294
1295 // If we didn't find any instance members, it can't be an implicit
1296 // member reference.
1297 if (Classes.empty())
1298 return IMA_Static;
1299
1300 // If the current context is not an instance method, it can't be
1301 // an implicit member reference.
Sebastian Redlf9780002010-11-26 16:28:07 +00001302 if (isStaticContext) {
1303 if (hasNonInstance)
1304 return IMA_Mixed_StaticContext;
1305
1306 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1307 // C++0x [expr.prim.general]p10:
1308 // An id-expression that denotes a non-static data member or non-static
1309 // member function of a class can only be used:
1310 // (...)
1311 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1312 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1313 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1314 if (isUnevaluatedExpression)
1315 return IMA_Mixed_StaticContext;
1316 }
1317
1318 return IMA_Error_StaticContext;
1319 }
John McCallaa81e162009-12-01 22:10:20 +00001320
Argyrios Kyrtzidis0d8dc462011-04-14 00:46:47 +00001321 CXXRecordDecl *
1322 contextClass = cast<CXXMethodDecl>(DC)->getParent()->getCanonicalDecl();
1323
1324 // [class.mfct.non-static]p3:
1325 // ...is used in the body of a non-static member function of class X,
1326 // if name lookup (3.4.1) resolves the name in the id-expression to a
1327 // non-static non-type member of some class C [...]
1328 // ...if C is not X or a base class of X, the class member access expression
1329 // is ill-formed.
1330 if (R.getNamingClass() &&
1331 contextClass != R.getNamingClass()->getCanonicalDecl() &&
1332 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
1333 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1334
John McCallaa81e162009-12-01 22:10:20 +00001335 // If we can prove that the current context is unrelated to all the
1336 // declaring classes, it can't be an implicit member reference (in
1337 // which case it's an error if any of those members are selected).
Argyrios Kyrtzidis0d8dc462011-04-14 00:46:47 +00001338 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
John McCallaa81e162009-12-01 22:10:20 +00001339 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1340
1341 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1342}
1343
1344/// Diagnose a reference to a field with no object available.
1345static void DiagnoseInstanceReference(Sema &SemaRef,
1346 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00001347 NamedDecl *rep,
1348 const DeclarationNameInfo &nameInfo) {
1349 SourceLocation Loc = nameInfo.getLoc();
John McCallaa81e162009-12-01 22:10:20 +00001350 SourceRange Range(Loc);
1351 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1352
John McCall5808ce42011-02-03 08:15:49 +00001353 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCallaa81e162009-12-01 22:10:20 +00001354 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1355 if (MD->isStatic()) {
1356 // "invalid use of member 'x' in static member function"
1357 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCall5808ce42011-02-03 08:15:49 +00001358 << Range << nameInfo.getName();
John McCallaa81e162009-12-01 22:10:20 +00001359 return;
1360 }
1361 }
1362
1363 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCall5808ce42011-02-03 08:15:49 +00001364 << nameInfo.getName() << Range;
John McCallaa81e162009-12-01 22:10:20 +00001365 return;
1366 }
1367
1368 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +00001369}
1370
John McCall578b69b2009-12-16 08:11:27 +00001371/// Diagnose an empty lookup.
1372///
1373/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001374bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1375 CorrectTypoContext CTC) {
John McCall578b69b2009-12-16 08:11:27 +00001376 DeclarationName Name = R.getLookupName();
1377
John McCall578b69b2009-12-16 08:11:27 +00001378 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001379 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001380 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1381 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001382 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001383 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001384 diagnostic_suggest = diag::err_undeclared_use_suggest;
1385 }
John McCall578b69b2009-12-16 08:11:27 +00001386
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001387 // If the original lookup was an unqualified lookup, fake an
1388 // unqualified lookup. This is useful when (for example) the
1389 // original lookup would not have found something because it was a
1390 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001391 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001392 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001393 if (isa<CXXRecordDecl>(DC)) {
1394 LookupQualifiedName(R, DC);
1395
1396 if (!R.empty()) {
1397 // Don't give errors about ambiguities in this lookup.
1398 R.suppressDiagnostics();
1399
1400 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1401 bool isInstance = CurMethod &&
1402 CurMethod->isInstance() &&
1403 DC == CurMethod->getParent();
1404
1405 // Give a code modification hint to insert 'this->'.
1406 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1407 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001408 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001409 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1410 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001411 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001412 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001413 if (DepMethod) {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001414 Diag(R.getNameLoc(), diagnostic) << Name
1415 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1416 QualType DepThisType = DepMethod->getThisType(Context);
1417 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1418 R.getNameLoc(), DepThisType, false);
1419 TemplateArgumentListInfo TList;
1420 if (ULE->hasExplicitTemplateArgs())
1421 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001422
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001423 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00001424 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001425 CXXDependentScopeMemberExpr *DepExpr =
1426 CXXDependentScopeMemberExpr::Create(
1427 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001428 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001429 R.getLookupNameInfo(), &TList);
1430 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001431 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001432 // FIXME: we should be able to handle this case too. It is correct
1433 // to add this-> here. This is a workaround for PR7947.
1434 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001435 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001436 } else {
John McCall578b69b2009-12-16 08:11:27 +00001437 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001438 }
John McCall578b69b2009-12-16 08:11:27 +00001439
1440 // Do we really want to note all of these?
1441 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1442 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1443
1444 // Tell the callee to try to recover.
1445 return false;
1446 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001447
1448 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001449 }
1450 }
1451
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001452 // We didn't find anything, so try to correct for a typo.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001453 DeclarationName Corrected;
Daniel Dunbardc32cdf2010-06-02 15:46:52 +00001454 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001455 if (!R.empty()) {
1456 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1457 if (SS.isEmpty())
1458 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1459 << FixItHint::CreateReplacement(R.getNameLoc(),
1460 R.getLookupName().getAsString());
1461 else
1462 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1463 << Name << computeDeclContext(SS, false) << R.getLookupName()
1464 << SS.getRange()
1465 << FixItHint::CreateReplacement(R.getNameLoc(),
1466 R.getLookupName().getAsString());
1467 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1468 Diag(ND->getLocation(), diag::note_previous_decl)
1469 << ND->getDeclName();
1470
1471 // Tell the callee to try to recover.
1472 return false;
1473 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001474
Douglas Gregoraaf87162010-04-14 20:04:41 +00001475 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1476 // FIXME: If we ended up with a typo for a type name or
1477 // Objective-C class name, we're in trouble because the parser
1478 // is in the wrong place to recover. Suggest the typo
1479 // correction, but don't make it a fix-it since we're not going
1480 // to recover well anyway.
1481 if (SS.isEmpty())
1482 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1483 else
1484 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1485 << Name << computeDeclContext(SS, false) << R.getLookupName()
1486 << SS.getRange();
1487
1488 // Don't try to recover; it won't work.
1489 return true;
1490 }
1491 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001492 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001493 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001494 if (SS.isEmpty())
Douglas Gregoraaf87162010-04-14 20:04:41 +00001495 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001496 else
Douglas Gregord203a162010-01-01 00:15:04 +00001497 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001498 << Name << computeDeclContext(SS, false) << Corrected
1499 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001500 return true;
1501 }
Douglas Gregord203a162010-01-01 00:15:04 +00001502 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001503 }
1504
1505 // Emit a special diagnostic for failed member lookups.
1506 // FIXME: computing the declaration context might fail here (?)
1507 if (!SS.isEmpty()) {
1508 Diag(R.getNameLoc(), diag::err_no_member)
1509 << Name << computeDeclContext(SS, false)
1510 << SS.getRange();
1511 return true;
1512 }
1513
John McCall578b69b2009-12-16 08:11:27 +00001514 // Give up, we can't recover.
1515 Diag(R.getNameLoc(), diagnostic) << Name;
1516 return true;
1517}
1518
Douglas Gregorca45da02010-11-02 20:36:02 +00001519ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1520 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001521 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1522 if (!IDecl)
1523 return 0;
1524 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1525 if (!ClassImpDecl)
1526 return 0;
Douglas Gregorca45da02010-11-02 20:36:02 +00001527 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001528 if (!property)
1529 return 0;
1530 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregorca45da02010-11-02 20:36:02 +00001531 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1532 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001533 return 0;
1534 return property;
1535}
1536
Douglas Gregorca45da02010-11-02 20:36:02 +00001537bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1538 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1539 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1540 if (!IDecl)
1541 return false;
1542 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1543 if (!ClassImpDecl)
1544 return false;
1545 if (ObjCPropertyImplDecl *PIDecl
1546 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1547 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1548 PIDecl->getPropertyIvarDecl())
1549 return false;
1550
1551 return true;
1552}
1553
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001554static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001555 LookupResult &Lookup,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001556 IdentifierInfo *II,
1557 SourceLocation NameLoc) {
1558 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001559 bool LookForIvars;
1560 if (Lookup.empty())
1561 LookForIvars = true;
1562 else if (CurMeth->isClassMethod())
1563 LookForIvars = false;
1564 else
1565 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahaniand0fbadd2011-01-26 00:57:01 +00001566 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1567 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001568 if (!LookForIvars)
1569 return 0;
1570
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001571 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1572 if (!IDecl)
1573 return 0;
1574 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001575 if (!ClassImpDecl)
1576 return 0;
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001577 bool DynamicImplSeen = false;
1578 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1579 if (!property)
1580 return 0;
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001581 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001582 DynamicImplSeen =
1583 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001584 // property implementation has a designated ivar. No need to assume a new
1585 // one.
1586 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1587 return 0;
1588 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001589 if (!DynamicImplSeen) {
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001590 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1591 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001592 NameLoc, NameLoc,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001593 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian75049662010-12-15 23:29:04 +00001594 ObjCIvarDecl::Private,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001595 (Expr *)0, true);
1596 ClassImpDecl->addDecl(Ivar);
1597 IDecl->makeDeclVisibleInContext(Ivar, false);
1598 property->setPropertyIvarDecl(Ivar);
1599 return Ivar;
1600 }
1601 return 0;
1602}
1603
John McCall60d7b3a2010-08-24 06:29:42 +00001604ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001605 CXXScopeSpec &SS,
1606 UnqualifiedId &Id,
1607 bool HasTrailingLParen,
1608 bool isAddressOfOperand) {
John McCallf7a1a742009-11-24 19:00:30 +00001609 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1610 "cannot be direct & operand and have a trailing lparen");
1611
1612 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001613 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001614
John McCall129e2df2009-11-30 22:42:35 +00001615 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001616
1617 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001618 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001619 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnara25777432010-08-11 22:01:17 +00001620 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001621
Abramo Bagnara25777432010-08-11 22:01:17 +00001622 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001623 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001624 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001625
John McCallf7a1a742009-11-24 19:00:30 +00001626 // C++ [temp.dep.expr]p3:
1627 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001628 // -- an identifier that was declared with a dependent type,
1629 // (note: handled after lookup)
1630 // -- a template-id that is dependent,
1631 // (note: handled in BuildTemplateIdExpr)
1632 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001633 // -- a nested-name-specifier that contains a class-name that
1634 // names a dependent type.
1635 // Determine whether this is a member of an unknown specialization;
1636 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001637 bool DependentID = false;
1638 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1639 Name.getCXXNameType()->isDependentType()) {
1640 DependentID = true;
1641 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001642 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001643 if (RequireCompleteDeclContext(SS, DC))
1644 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001645 } else {
1646 DependentID = true;
1647 }
1648 }
1649
Chris Lattner337e5502011-02-18 01:27:55 +00001650 if (DependentID)
Abramo Bagnara25777432010-08-11 22:01:17 +00001651 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001652 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001653
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001654 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001655 // Perform the required lookup.
Abramo Bagnara25777432010-08-11 22:01:17 +00001656 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001657 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001658 // Lookup the template name again to correctly establish the context in
1659 // which it was found. This is really unfortunate as we already did the
1660 // lookup to determine that it was a template name in the first place. If
1661 // this becomes a performance hit, we can work harder to preserve those
1662 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001663 bool MemberOfUnknownSpecialization;
1664 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1665 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001666
1667 if (MemberOfUnknownSpecialization ||
1668 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1669 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1670 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001671 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001672 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001673 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001675 // If the result might be in a dependent base class, this is a dependent
1676 // id-expression.
1677 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1678 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1679 TemplateArgs);
1680
John McCallf7a1a742009-11-24 19:00:30 +00001681 // If this reference is in an Objective-C method, then we need to do
1682 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001683 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001684 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001685 if (E.isInvalid())
1686 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Chris Lattner337e5502011-02-18 01:27:55 +00001688 if (Expr *Ex = E.takeAs<Expr>())
1689 return Owned(Ex);
1690
1691 // Synthesize ivars lazily.
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001692 if (getLangOptions().ObjCDefaultSynthProperties &&
1693 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahaniande267602010-11-17 19:41:23 +00001694 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1695 if (const ObjCPropertyDecl *Property =
1696 canSynthesizeProvisionalIvar(II)) {
1697 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1698 Diag(Property->getLocation(), diag::note_property_declare);
1699 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001700 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1701 isAddressOfOperand);
Fariborz Jahaniande267602010-11-17 19:41:23 +00001702 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001703 }
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001704 // for further use, this must be set to false if in class method.
1705 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001706 }
Chris Lattner8a934232008-03-31 00:36:02 +00001707 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001708
John McCallf7a1a742009-11-24 19:00:30 +00001709 if (R.isAmbiguous())
1710 return ExprError();
1711
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001712 // Determine whether this name might be a candidate for
1713 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001714 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001715
John McCallf7a1a742009-11-24 19:00:30 +00001716 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001717 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001718 // in C90, extension in C99, forbidden in C++).
1719 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1720 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1721 if (D) R.addDecl(D);
1722 }
1723
1724 // If this name wasn't predeclared and if this is not a function
1725 // call, diagnose the problem.
1726 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001727 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001728 return ExprError();
1729
1730 assert(!R.empty() &&
1731 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001732
1733 // If we found an Objective-C instance variable, let
1734 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001735 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001736 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1737 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001738 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001739 assert(E.isInvalid() || E.get());
1740 return move(E);
1741 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001742 }
1743 }
Mike Stump1eb44332009-09-09 15:08:12 +00001744
John McCallf7a1a742009-11-24 19:00:30 +00001745 // This is guaranteed from this point on.
1746 assert(!R.empty() || ADL);
1747
John McCallaa81e162009-12-01 22:10:20 +00001748 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001749 // C++ [class.mfct.non-static]p3:
1750 // When an id-expression that is not part of a class member access
1751 // syntax and not used to form a pointer to member is used in the
1752 // body of a non-static member function of class X, if name lookup
1753 // resolves the name in the id-expression to a non-static non-type
1754 // member of some class C, the id-expression is transformed into a
1755 // class member access expression using (*this) as the
1756 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001757 //
1758 // But we don't actually need to do this for '&' operands if R
1759 // resolved to a function or overloaded function set, because the
1760 // expression is ill-formed if it actually works out to be a
1761 // non-static member function:
1762 //
1763 // C++ [expr.ref]p4:
1764 // Otherwise, if E1.E2 refers to a non-static member function. . .
1765 // [t]he expression can be used only as the left-hand operand of a
1766 // member function call.
1767 //
1768 // There are other safeguards against such uses, but it's important
1769 // to get this right here so that we don't end up making a
1770 // spuriously dependent expression if we're inside a dependent
1771 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001772 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001773 bool MightBeImplicitMember;
1774 if (!isAddressOfOperand)
1775 MightBeImplicitMember = true;
1776 else if (!SS.isEmpty())
1777 MightBeImplicitMember = false;
1778 else if (R.isOverloadedResult())
1779 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001780 else if (R.isUnresolvableResult())
1781 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001782 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001783 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1784 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001785
1786 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001787 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001788 }
1789
John McCallf7a1a742009-11-24 19:00:30 +00001790 if (TemplateArgs)
1791 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001792
John McCallf7a1a742009-11-24 19:00:30 +00001793 return BuildDeclarationNameExpr(SS, R, ADL);
1794}
1795
John McCall3b4294e2009-12-16 12:17:52 +00001796/// Builds an expression which might be an implicit member expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001797ExprResult
John McCall3b4294e2009-12-16 12:17:52 +00001798Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1799 LookupResult &R,
1800 const TemplateArgumentListInfo *TemplateArgs) {
1801 switch (ClassifyImplicitMemberAccess(*this, R)) {
1802 case IMA_Instance:
1803 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1804
John McCall3b4294e2009-12-16 12:17:52 +00001805 case IMA_Mixed:
1806 case IMA_Mixed_Unrelated:
1807 case IMA_Unresolved:
1808 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1809
1810 case IMA_Static:
1811 case IMA_Mixed_StaticContext:
1812 case IMA_Unresolved_StaticContext:
1813 if (TemplateArgs)
1814 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1815 return BuildDeclarationNameExpr(SS, R, false);
1816
1817 case IMA_Error_StaticContext:
1818 case IMA_Error_Unrelated:
John McCall5808ce42011-02-03 08:15:49 +00001819 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1820 R.getLookupNameInfo());
John McCall3b4294e2009-12-16 12:17:52 +00001821 return ExprError();
1822 }
1823
1824 llvm_unreachable("unexpected instance member access kind");
1825 return ExprError();
1826}
1827
John McCall129e2df2009-11-30 22:42:35 +00001828/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1829/// declaration name, generally during template instantiation.
1830/// There's a large number of things which don't need to be done along
1831/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001832ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001833Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001834 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001835 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001836 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001837 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001838
John McCall77bb1aa2010-05-01 00:40:08 +00001839 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001840 return ExprError();
1841
Abramo Bagnara25777432010-08-11 22:01:17 +00001842 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001843 LookupQualifiedName(R, DC);
1844
1845 if (R.isAmbiguous())
1846 return ExprError();
1847
1848 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001849 Diag(NameInfo.getLoc(), diag::err_no_member)
1850 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001851 return ExprError();
1852 }
1853
1854 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1855}
1856
1857/// LookupInObjCMethod - The parser has read a name in, and Sema has
1858/// detected that we're currently inside an ObjC method. Perform some
1859/// additional lookup.
1860///
1861/// Ideally, most of this would be done by lookup, but there's
1862/// actually quite a lot of extra work involved.
1863///
1864/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001865ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001866Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001867 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001868 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001869 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001870
John McCallf7a1a742009-11-24 19:00:30 +00001871 // There are two cases to handle here. 1) scoped lookup could have failed,
1872 // in which case we should look for an ivar. 2) scoped lookup could have
1873 // found a decl, but that decl is outside the current instance method (i.e.
1874 // a global variable). In these two cases, we do a lookup for an ivar with
1875 // this name, if the lookup sucedes, we replace it our current decl.
1876
1877 // If we're in a class method, we don't normally want to look for
1878 // ivars. But if we don't find anything else, and there's an
1879 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001880 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001881
1882 bool LookForIvars;
1883 if (Lookup.empty())
1884 LookForIvars = true;
1885 else if (IsClassMethod)
1886 LookForIvars = false;
1887 else
1888 LookForIvars = (Lookup.isSingleResult() &&
1889 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001890 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001891 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001892 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001893 ObjCInterfaceDecl *ClassDeclared;
1894 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1895 // Diagnose using an ivar in a class method.
1896 if (IsClassMethod)
1897 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1898 << IV->getDeclName());
1899
1900 // If we're referencing an invalid decl, just return this as a silent
1901 // error node. The error diagnostic was already emitted on the decl.
1902 if (IV->isInvalidDecl())
1903 return ExprError();
1904
1905 // Check if referencing a field with __attribute__((deprecated)).
1906 if (DiagnoseUseOfDecl(IV, Loc))
1907 return ExprError();
1908
1909 // Diagnose the use of an ivar outside of the declaring class.
1910 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1911 ClassDeclared != IFace)
1912 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1913
1914 // FIXME: This should use a new expr for a direct reference, don't
1915 // turn this into Self->ivar, just return a BareIVarExpr or something.
1916 IdentifierInfo &II = Context.Idents.get("self");
1917 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001918 SelfName.setIdentifier(&II, SourceLocation());
John McCallf7a1a742009-11-24 19:00:30 +00001919 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00001920 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001921 SelfName, false, false);
1922 if (SelfExpr.isInvalid())
1923 return ExprError();
1924
John Wiegley429bb272011-04-08 18:41:53 +00001925 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1926 if (SelfExpr.isInvalid())
1927 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001928
John McCallf7a1a742009-11-24 19:00:30 +00001929 MarkDeclarationReferenced(Loc, IV);
Fariborz Jahanianb8f17ab2011-04-12 23:39:33 +00001930 Expr *base = SelfExpr.take();
1931 base = base->IgnoreParenImpCasts();
1932 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(base)) {
1933 const NamedDecl *ND = DE->getDecl();
1934 if (!isa<ImplicitParamDecl>(ND)) {
1935 Diag(Loc, diag::error_implicit_ivar_access)
1936 << IV->getDeclName();
1937 Diag(ND->getLocation(), diag::note_declared_at);
1938 return ExprError();
1939 }
1940 }
John McCallf7a1a742009-11-24 19:00:30 +00001941 return Owned(new (Context)
1942 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00001943 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001944 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001945 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001946 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001947 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001948 ObjCInterfaceDecl *ClassDeclared;
1949 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1950 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1951 IFace == ClassDeclared)
1952 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1953 }
1954 }
1955
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001956 if (Lookup.empty() && II && AllowBuiltinCreation) {
1957 // FIXME. Consolidate this with similar code in LookupName.
1958 if (unsigned BuiltinID = II->getBuiltinID()) {
1959 if (!(getLangOptions().CPlusPlus &&
1960 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1961 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1962 S, Lookup.isForRedeclaration(),
1963 Lookup.getNameLoc());
1964 if (D) Lookup.addDecl(D);
1965 }
1966 }
1967 }
John McCallf7a1a742009-11-24 19:00:30 +00001968 // Sentinel value saying that we didn't do anything special.
1969 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001970}
John McCallba135432009-11-21 08:51:07 +00001971
John McCall6bb80172010-03-30 21:47:33 +00001972/// \brief Cast a base object to a member's actual type.
1973///
1974/// Logically this happens in three phases:
1975///
1976/// * First we cast from the base type to the naming class.
1977/// The naming class is the class into which we were looking
1978/// when we found the member; it's the qualifier type if a
1979/// qualifier was provided, and otherwise it's the base type.
1980///
1981/// * Next we cast from the naming class to the declaring class.
1982/// If the member we found was brought into a class's scope by
1983/// a using declaration, this is that class; otherwise it's
1984/// the class declaring the member.
1985///
1986/// * Finally we cast from the declaring class to the "true"
1987/// declaring class of the member. This conversion does not
1988/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00001989ExprResult
1990Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001991 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001992 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001993 NamedDecl *Member) {
1994 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1995 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00001996 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001997
Douglas Gregor5fccd362010-03-03 23:55:11 +00001998 QualType DestRecordType;
1999 QualType DestType;
2000 QualType FromRecordType;
2001 QualType FromType = From->getType();
2002 bool PointerConversions = false;
2003 if (isa<FieldDecl>(Member)) {
2004 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002005
Douglas Gregor5fccd362010-03-03 23:55:11 +00002006 if (FromType->getAs<PointerType>()) {
2007 DestType = Context.getPointerType(DestRecordType);
2008 FromRecordType = FromType->getPointeeType();
2009 PointerConversions = true;
2010 } else {
2011 DestType = DestRecordType;
2012 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002013 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002014 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2015 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002016 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002017
Douglas Gregor5fccd362010-03-03 23:55:11 +00002018 DestType = Method->getThisType(Context);
2019 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002020
Douglas Gregor5fccd362010-03-03 23:55:11 +00002021 if (FromType->getAs<PointerType>()) {
2022 FromRecordType = FromType->getPointeeType();
2023 PointerConversions = true;
2024 } else {
2025 FromRecordType = FromType;
2026 DestType = DestRecordType;
2027 }
2028 } else {
2029 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002030 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002031 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002032
Douglas Gregor5fccd362010-03-03 23:55:11 +00002033 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002034 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002035
Douglas Gregor5fccd362010-03-03 23:55:11 +00002036 // If the unqualified types are the same, no conversion is necessary.
2037 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002038 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002039
John McCall6bb80172010-03-30 21:47:33 +00002040 SourceRange FromRange = From->getSourceRange();
2041 SourceLocation FromLoc = FromRange.getBegin();
2042
John McCall5baba9d2010-08-25 10:28:54 +00002043 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00002044
Douglas Gregor5fccd362010-03-03 23:55:11 +00002045 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002046 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002047 // class name.
2048 //
2049 // If the member was a qualified name and the qualified referred to a
2050 // specific base subobject type, we'll cast to that intermediate type
2051 // first and then to the object in which the member is declared. That allows
2052 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2053 //
2054 // class Base { public: int x; };
2055 // class Derived1 : public Base { };
2056 // class Derived2 : public Base { };
2057 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2058 //
2059 // void VeryDerived::f() {
2060 // x = 17; // error: ambiguous base subobjects
2061 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2062 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002063 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002064 QualType QType = QualType(Qualifier->getAsType(), 0);
2065 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2066 assert(QType->isRecordType() && "lookup done with non-record type");
2067
2068 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2069
2070 // In C++98, the qualifier type doesn't actually have to be a base
2071 // type of the object type, in which case we just ignore it.
2072 // Otherwise build the appropriate casts.
2073 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002074 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002075 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002076 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002077 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002078
Douglas Gregor5fccd362010-03-03 23:55:11 +00002079 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002080 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002081 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2082 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002083
2084 FromType = QType;
2085 FromRecordType = QRecordType;
2086
2087 // If the qualifier type was the same as the destination type,
2088 // we're done.
2089 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002090 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002091 }
2092 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002093
John McCall6bb80172010-03-30 21:47:33 +00002094 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002095
John McCall6bb80172010-03-30 21:47:33 +00002096 // If we actually found the member through a using declaration, cast
2097 // down to the using declaration's type.
2098 //
2099 // Pointer equality is fine here because only one declaration of a
2100 // class ever has member declarations.
2101 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2102 assert(isa<UsingShadowDecl>(FoundDecl));
2103 QualType URecordType = Context.getTypeDeclType(
2104 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2105
2106 // We only need to do this if the naming-class to declaring-class
2107 // conversion is non-trivial.
2108 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2109 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002110 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002111 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002112 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002113 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002114
John McCall6bb80172010-03-30 21:47:33 +00002115 QualType UType = URecordType;
2116 if (PointerConversions)
2117 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002118 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2119 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002120 FromType = UType;
2121 FromRecordType = URecordType;
2122 }
2123
2124 // We don't do access control for the conversion from the
2125 // declaring class to the true declaring class.
2126 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002127 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002128
John McCallf871d0c2010-08-07 06:22:56 +00002129 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002130 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2131 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002132 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002133 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002134
John Wiegley429bb272011-04-08 18:41:53 +00002135 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2136 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002137}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002138
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002139/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00002140static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00002141 const CXXScopeSpec &SS, ValueDecl *Member,
John McCall161755a2010-04-06 21:38:20 +00002142 DeclAccessPair FoundDecl,
Abramo Bagnara25777432010-08-11 22:01:17 +00002143 const DeclarationNameInfo &MemberNameInfo,
2144 QualType Ty,
John McCallf89e55a2010-11-18 06:31:45 +00002145 ExprValueKind VK, ExprObjectKind OK,
John McCallf7a1a742009-11-24 19:00:30 +00002146 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregor40d96a62011-02-28 21:54:11 +00002147 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnara25777432010-08-11 22:01:17 +00002148 Member, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002149 TemplateArgs, Ty, VK, OK);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002150}
2151
John McCalldfa1edb2010-11-23 20:48:44 +00002152static ExprResult
2153BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2154 const CXXScopeSpec &SS, FieldDecl *Field,
2155 DeclAccessPair FoundDecl,
2156 const DeclarationNameInfo &MemberNameInfo) {
2157 // x.a is an l-value if 'a' has a reference type. Otherwise:
2158 // x.a is an l-value/x-value/pr-value if the base is (and note
2159 // that *x is always an l-value), except that if the base isn't
2160 // an ordinary object then we must have an rvalue.
2161 ExprValueKind VK = VK_LValue;
2162 ExprObjectKind OK = OK_Ordinary;
2163 if (!IsArrow) {
2164 if (BaseExpr->getObjectKind() == OK_Ordinary)
2165 VK = BaseExpr->getValueKind();
2166 else
2167 VK = VK_RValue;
2168 }
2169 if (VK != VK_RValue && Field->isBitField())
2170 OK = OK_BitField;
2171
2172 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2173 QualType MemberType = Field->getType();
2174 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2175 MemberType = Ref->getPointeeType();
2176 VK = VK_LValue;
2177 } else {
2178 QualType BaseType = BaseExpr->getType();
2179 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2180
2181 Qualifiers BaseQuals = BaseType.getQualifiers();
2182
2183 // GC attributes are never picked up by members.
2184 BaseQuals.removeObjCGCAttr();
2185
2186 // CVR attributes from the base are picked up by members,
2187 // except that 'mutable' members don't pick up 'const'.
2188 if (Field->isMutable()) BaseQuals.removeConst();
2189
2190 Qualifiers MemberQuals
2191 = S.Context.getCanonicalType(MemberType).getQualifiers();
2192
2193 // TR 18037 does not allow fields to be declared with address spaces.
2194 assert(!MemberQuals.hasAddressSpace());
2195
2196 Qualifiers Combined = BaseQuals + MemberQuals;
2197 if (Combined != MemberQuals)
2198 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2199 }
2200
2201 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
John Wiegley429bb272011-04-08 18:41:53 +00002202 ExprResult Base =
2203 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2204 FoundDecl, Field);
2205 if (Base.isInvalid())
John McCalldfa1edb2010-11-23 20:48:44 +00002206 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00002207 return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
John McCalldfa1edb2010-11-23 20:48:44 +00002208 Field, FoundDecl, MemberNameInfo,
2209 MemberType, VK, OK));
2210}
2211
John McCallaa81e162009-12-01 22:10:20 +00002212/// Builds an implicit member access expression. The current context
2213/// is known to be an instance method, and the given unqualified lookup
2214/// set is known to contain only instance members, at least one of which
2215/// is from an appropriate type.
John McCall60d7b3a2010-08-24 06:29:42 +00002216ExprResult
John McCallaa81e162009-12-01 22:10:20 +00002217Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2218 LookupResult &R,
2219 const TemplateArgumentListInfo *TemplateArgs,
2220 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00002221 assert(!R.empty() && !R.isAmbiguous());
2222
John McCall5808ce42011-02-03 08:15:49 +00002223 SourceLocation loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00002224
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002225 // We may have found a field within an anonymous union or struct
2226 // (C++ [class.union]).
John McCallf7a1a742009-11-24 19:00:30 +00002227 // FIXME: template-ids inside anonymous structs?
Francois Pichet87c2e122010-11-21 06:08:52 +00002228 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCall5808ce42011-02-03 08:15:49 +00002229 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet87c2e122010-11-21 06:08:52 +00002230
John McCall5808ce42011-02-03 08:15:49 +00002231 // If this is known to be an instance access, go ahead and build an
2232 // implicit 'this' expression now.
John McCallaa81e162009-12-01 22:10:20 +00002233 // 'this' expression now.
John McCall5808ce42011-02-03 08:15:49 +00002234 CXXMethodDecl *method = tryCaptureCXXThis();
2235 assert(method && "didn't correctly pre-flight capture of 'this'");
2236
2237 QualType thisType = method->getThisType(Context);
2238 Expr *baseExpr = 0; // null signifies implicit access
John McCallaa81e162009-12-01 22:10:20 +00002239 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00002240 SourceLocation Loc = R.getNameLoc();
2241 if (SS.getRange().isValid())
2242 Loc = SS.getRange().getBegin();
John McCall5808ce42011-02-03 08:15:49 +00002243 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00002244 }
2245
John McCall5808ce42011-02-03 08:15:49 +00002246 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCallaa81e162009-12-01 22:10:20 +00002247 /*OpLoc*/ SourceLocation(),
2248 /*IsArrow*/ true,
John McCallc2233c52010-01-15 08:34:02 +00002249 SS,
2250 /*FirstQualifierInScope*/ 0,
2251 R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00002252}
2253
John McCallf7a1a742009-11-24 19:00:30 +00002254bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002255 const LookupResult &R,
2256 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002257 // Only when used directly as the postfix-expression of a call.
2258 if (!HasTrailingLParen)
2259 return false;
2260
2261 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002262 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002263 return false;
2264
2265 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002266 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002267 return false;
2268
2269 // Turn off ADL when we find certain kinds of declarations during
2270 // normal lookup:
2271 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2272 NamedDecl *D = *I;
2273
2274 // C++0x [basic.lookup.argdep]p3:
2275 // -- a declaration of a class member
2276 // Since using decls preserve this property, we check this on the
2277 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002278 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002279 return false;
2280
2281 // C++0x [basic.lookup.argdep]p3:
2282 // -- a block-scope function declaration that is not a
2283 // using-declaration
2284 // NOTE: we also trigger this for function templates (in fact, we
2285 // don't check the decl type at all, since all other decl types
2286 // turn off ADL anyway).
2287 if (isa<UsingShadowDecl>(D))
2288 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2289 else if (D->getDeclContext()->isFunctionOrMethod())
2290 return false;
2291
2292 // C++0x [basic.lookup.argdep]p3:
2293 // -- a declaration that is neither a function or a function
2294 // template
2295 // And also for builtin functions.
2296 if (isa<FunctionDecl>(D)) {
2297 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2298
2299 // But also builtin functions.
2300 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2301 return false;
2302 } else if (!isa<FunctionTemplateDecl>(D))
2303 return false;
2304 }
2305
2306 return true;
2307}
2308
2309
John McCallba135432009-11-21 08:51:07 +00002310/// Diagnoses obvious problems with the use of the given declaration
2311/// as an expression. This is only actually called for lookups that
2312/// were not overloaded, and it doesn't promise that the declaration
2313/// will in fact be used.
2314static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2315 if (isa<TypedefDecl>(D)) {
2316 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2317 return true;
2318 }
2319
2320 if (isa<ObjCInterfaceDecl>(D)) {
2321 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2322 return true;
2323 }
2324
2325 if (isa<NamespaceDecl>(D)) {
2326 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2327 return true;
2328 }
2329
2330 return false;
2331}
2332
John McCall60d7b3a2010-08-24 06:29:42 +00002333ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002334Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002335 LookupResult &R,
2336 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002337 // If this is a single, fully-resolved result and we don't need ADL,
2338 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002339 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002340 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2341 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002342
2343 // We only need to check the declaration if there's exactly one
2344 // result, because in the overloaded case the results can only be
2345 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002346 if (R.isSingleResult() &&
2347 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002348 return ExprError();
2349
John McCallc373d482010-01-27 01:50:18 +00002350 // Otherwise, just build an unresolved lookup expression. Suppress
2351 // any lookup-related diagnostics; we'll hash these out later, when
2352 // we've picked a target.
2353 R.suppressDiagnostics();
2354
John McCallba135432009-11-21 08:51:07 +00002355 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002356 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002357 SS.getWithLocInContext(Context),
2358 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002359 NeedsADL, R.isOverloadedResult(),
2360 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002361
2362 return Owned(ULE);
2363}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002364
John McCallba135432009-11-21 08:51:07 +00002365/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002366ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002367Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002368 const DeclarationNameInfo &NameInfo,
2369 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002370 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002371 assert(!isa<FunctionTemplateDecl>(D) &&
2372 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002373
Abramo Bagnara25777432010-08-11 22:01:17 +00002374 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002375 if (CheckDeclInExpr(*this, Loc, D))
2376 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002377
Douglas Gregor9af2f522009-12-01 16:58:18 +00002378 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2379 // Specifically diagnose references to class templates that are missing
2380 // a template argument list.
2381 Diag(Loc, diag::err_template_decl_ref)
2382 << Template << SS.getRange();
2383 Diag(Template->getLocation(), diag::note_template_decl_here);
2384 return ExprError();
2385 }
2386
2387 // Make sure that we're referring to a value.
2388 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2389 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002390 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002391 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002392 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002393 return ExprError();
2394 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002395
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002396 // Check whether this declaration can be used. Note that we suppress
2397 // this check when we're going to perform argument-dependent lookup
2398 // on this function name, because this might not be the function
2399 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002400 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002401 return ExprError();
2402
Steve Naroffdd972f22008-09-05 22:11:13 +00002403 // Only create DeclRefExpr's for valid Decl's.
2404 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002405 return ExprError();
2406
John McCall5808ce42011-02-03 08:15:49 +00002407 // Handle members of anonymous structs and unions. If we got here,
2408 // and the reference is to a class member indirect field, then this
2409 // must be the subject of a pointer-to-member expression.
2410 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2411 if (!indirectField->isCXXClassMember())
2412 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2413 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002414
Chris Lattner639e2d32008-10-20 05:16:36 +00002415 // If the identifier reference is inside a block, and it refers to a value
2416 // that is outside the block, create a BlockDeclRefExpr instead of a
2417 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2418 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002419 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002420 // We do not do this for things like enum constants, global variables, etc,
2421 // as they do not get snapshotted.
2422 //
John McCall6b5a61b2011-02-07 10:33:21 +00002423 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002424 case CR_Error:
2425 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002426
John McCall469a1eb2011-02-02 13:00:07 +00002427 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002428 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2429 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2430
2431 case CR_CaptureByRef:
2432 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2433 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002434
2435 case CR_NoCapture: {
2436 // If this reference is not in a block or if the referenced
2437 // variable is within the block, create a normal DeclRefExpr.
2438
2439 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002440 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002441
2442 switch (D->getKind()) {
2443 // Ignore all the non-ValueDecl kinds.
2444#define ABSTRACT_DECL(kind)
2445#define VALUE(type, base)
2446#define DECL(type, base) \
2447 case Decl::type:
2448#include "clang/AST/DeclNodes.inc"
2449 llvm_unreachable("invalid value decl kind");
2450 return ExprError();
2451
2452 // These shouldn't make it here.
2453 case Decl::ObjCAtDefsField:
2454 case Decl::ObjCIvar:
2455 llvm_unreachable("forming non-member reference to ivar?");
2456 return ExprError();
2457
2458 // Enum constants are always r-values and never references.
2459 // Unresolved using declarations are dependent.
2460 case Decl::EnumConstant:
2461 case Decl::UnresolvedUsingValue:
2462 valueKind = VK_RValue;
2463 break;
2464
2465 // Fields and indirect fields that got here must be for
2466 // pointer-to-member expressions; we just call them l-values for
2467 // internal consistency, because this subexpression doesn't really
2468 // exist in the high-level semantics.
2469 case Decl::Field:
2470 case Decl::IndirectField:
2471 assert(getLangOptions().CPlusPlus &&
2472 "building reference to field in C?");
2473
2474 // These can't have reference type in well-formed programs, but
2475 // for internal consistency we do this anyway.
2476 type = type.getNonReferenceType();
2477 valueKind = VK_LValue;
2478 break;
2479
2480 // Non-type template parameters are either l-values or r-values
2481 // depending on the type.
2482 case Decl::NonTypeTemplateParm: {
2483 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2484 type = reftype->getPointeeType();
2485 valueKind = VK_LValue; // even if the parameter is an r-value reference
2486 break;
2487 }
2488
2489 // For non-references, we need to strip qualifiers just in case
2490 // the template parameter was declared as 'const int' or whatever.
2491 valueKind = VK_RValue;
2492 type = type.getUnqualifiedType();
2493 break;
2494 }
2495
2496 case Decl::Var:
2497 // In C, "extern void blah;" is valid and is an r-value.
2498 if (!getLangOptions().CPlusPlus &&
2499 !type.hasQualifiers() &&
2500 type->isVoidType()) {
2501 valueKind = VK_RValue;
2502 break;
2503 }
2504 // fallthrough
2505
2506 case Decl::ImplicitParam:
2507 case Decl::ParmVar:
2508 // These are always l-values.
2509 valueKind = VK_LValue;
2510 type = type.getNonReferenceType();
2511 break;
2512
2513 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002514 const FunctionType *fty = type->castAs<FunctionType>();
2515
2516 // If we're referring to a function with an __unknown_anytype
2517 // result type, make the entire expression __unknown_anytype.
2518 if (fty->getResultType() == Context.UnknownAnyTy) {
2519 type = Context.UnknownAnyTy;
2520 valueKind = VK_RValue;
2521 break;
2522 }
2523
John McCall76a40212011-02-09 01:13:10 +00002524 // Functions are l-values in C++.
2525 if (getLangOptions().CPlusPlus) {
2526 valueKind = VK_LValue;
2527 break;
2528 }
2529
2530 // C99 DR 316 says that, if a function type comes from a
2531 // function definition (without a prototype), that type is only
2532 // used for checking compatibility. Therefore, when referencing
2533 // the function, we pretend that we don't have the full function
2534 // type.
John McCall755d8492011-04-12 00:42:48 +00002535 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2536 isa<FunctionProtoType>(fty))
2537 type = Context.getFunctionNoProtoType(fty->getResultType(),
2538 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002539
2540 // Functions are r-values in C.
2541 valueKind = VK_RValue;
2542 break;
2543 }
2544
2545 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002546 // If we're referring to a method with an __unknown_anytype
2547 // result type, make the entire expression __unknown_anytype.
2548 // This should only be possible with a type written directly.
2549 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2550 if (proto->getResultType() == Context.UnknownAnyTy) {
2551 type = Context.UnknownAnyTy;
2552 valueKind = VK_RValue;
2553 break;
2554 }
2555
John McCall76a40212011-02-09 01:13:10 +00002556 // C++ methods are l-values if static, r-values if non-static.
2557 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2558 valueKind = VK_LValue;
2559 break;
2560 }
2561 // fallthrough
2562
2563 case Decl::CXXConversion:
2564 case Decl::CXXDestructor:
2565 case Decl::CXXConstructor:
2566 valueKind = VK_RValue;
2567 break;
2568 }
2569
2570 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2571 }
2572
John McCall469a1eb2011-02-02 13:00:07 +00002573 }
John McCallf89e55a2010-11-18 06:31:45 +00002574
John McCall6b5a61b2011-02-07 10:33:21 +00002575 llvm_unreachable("unknown capture result");
2576 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002577}
2578
John McCall755d8492011-04-12 00:42:48 +00002579ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002580 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002581
Reid Spencer5f016e22007-07-11 17:01:13 +00002582 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002583 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002584 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2585 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2586 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002587 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002588
Chris Lattnerfa28b302008-01-12 08:14:25 +00002589 // Pre-defined identifiers are of type char[x], where x is the length of the
2590 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002591
Anders Carlsson3a082d82009-09-08 18:24:21 +00002592 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002593 if (!currentDecl && getCurBlock())
2594 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002595 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002596 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002597 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002598 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002599
Anders Carlsson773f3972009-09-11 01:22:35 +00002600 QualType ResTy;
2601 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2602 ResTy = Context.DependentTy;
2603 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002604 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002605
Anders Carlsson773f3972009-09-11 01:22:35 +00002606 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002607 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002608 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2609 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002610 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002611}
2612
John McCall60d7b3a2010-08-24 06:29:42 +00002613ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002614 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002615 bool Invalid = false;
2616 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2617 if (Invalid)
2618 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002619
Benjamin Kramerddeea562010-02-27 13:44:12 +00002620 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2621 PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002622 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002623 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002624
Chris Lattnere8337df2009-12-30 21:19:39 +00002625 QualType Ty;
2626 if (!getLangOptions().CPlusPlus)
2627 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2628 else if (Literal.isWide())
2629 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002630 else if (Literal.isMultiChar())
2631 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002632 else
2633 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002634
Sebastian Redle91b3bc2009-01-20 22:23:13 +00002635 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2636 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00002637 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002638}
2639
John McCall60d7b3a2010-08-24 06:29:42 +00002640ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002641 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002642 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2643 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002644 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00002645 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002646 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002647 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002648 }
Ted Kremenek28396602009-01-13 23:19:12 +00002649
Reid Spencer5f016e22007-07-11 17:01:13 +00002650 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002651 // Add padding so that NumericLiteralParser can overread by one character.
2652 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002653 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002654
Reid Spencer5f016e22007-07-11 17:01:13 +00002655 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002656 bool Invalid = false;
2657 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2658 if (Invalid)
2659 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002660
Mike Stump1eb44332009-09-09 15:08:12 +00002661 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002662 Tok.getLocation(), PP);
2663 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002664 return ExprError();
2665
Chris Lattner5d661452007-08-26 03:42:43 +00002666 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002667
Chris Lattner5d661452007-08-26 03:42:43 +00002668 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002669 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002670 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002671 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002672 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002673 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002674 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002675 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002676
2677 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2678
John McCall94c939d2009-12-24 09:08:04 +00002679 using llvm::APFloat;
2680 APFloat Val(Format);
2681
2682 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002683
2684 // Overflow is always an error, but underflow is only an error if
2685 // we underflowed to zero (APFloat reports denormals as underflow).
2686 if ((result & APFloat::opOverflow) ||
2687 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002688 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002689 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002690 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002691 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002692 APFloat::getLargest(Format).toString(buffer);
2693 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002694 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002695 APFloat::getSmallest(Format).toString(buffer);
2696 }
2697
2698 Diag(Tok.getLocation(), diagnostic)
2699 << Ty
2700 << llvm::StringRef(buffer.data(), buffer.size());
2701 }
2702
2703 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002704 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002705
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002706 if (Ty == Context.DoubleTy) {
2707 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002708 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002709 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2710 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002711 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002712 }
2713 }
Chris Lattner5d661452007-08-26 03:42:43 +00002714 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002715 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002716 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002717 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002718
Neil Boothb9449512007-08-29 22:00:19 +00002719 // long long is a C99 feature.
2720 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002721 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002722 Diag(Tok.getLocation(), diag::ext_longlong);
2723
Reid Spencer5f016e22007-07-11 17:01:13 +00002724 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00002725 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002726
Reid Spencer5f016e22007-07-11 17:01:13 +00002727 if (Literal.GetIntegerValue(ResultVal)) {
2728 // If this value didn't fit into uintmax_t, warn and force to ull.
2729 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002730 Ty = Context.UnsignedLongLongTy;
2731 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002732 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002733 } else {
2734 // If this value fits into a ULL, try to figure out what else it fits into
2735 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002736
Reid Spencer5f016e22007-07-11 17:01:13 +00002737 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2738 // be an unsigned int.
2739 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2740
2741 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002742 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002743 if (!Literal.isLong && !Literal.isLongLong) {
2744 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002745 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002746
Reid Spencer5f016e22007-07-11 17:01:13 +00002747 // Does it fit in a unsigned int?
2748 if (ResultVal.isIntN(IntSize)) {
2749 // Does it fit in a signed int?
2750 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002751 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002752 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002753 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002754 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002755 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002756 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002757
Reid Spencer5f016e22007-07-11 17:01:13 +00002758 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002759 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002760 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002761
Reid Spencer5f016e22007-07-11 17:01:13 +00002762 // Does it fit in a unsigned long?
2763 if (ResultVal.isIntN(LongSize)) {
2764 // Does it fit in a signed long?
2765 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002766 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002767 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002768 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002769 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002770 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002771 }
2772
Reid Spencer5f016e22007-07-11 17:01:13 +00002773 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002774 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002775 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002776
Reid Spencer5f016e22007-07-11 17:01:13 +00002777 // Does it fit in a unsigned long long?
2778 if (ResultVal.isIntN(LongLongSize)) {
2779 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002780 // To be compatible with MSVC, hex integer literals ending with the
2781 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002782 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2783 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002784 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002785 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002786 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002787 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002788 }
2789 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002790
Reid Spencer5f016e22007-07-11 17:01:13 +00002791 // If we still couldn't decide a type, we probably have something that
2792 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002793 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002794 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002795 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002796 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002797 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002798
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002799 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002800 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002801 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002802 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002803 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002804
Chris Lattner5d661452007-08-26 03:42:43 +00002805 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2806 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002807 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002808 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002809
2810 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002811}
2812
John McCall60d7b3a2010-08-24 06:29:42 +00002813ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCall9ae2f072010-08-23 23:25:46 +00002814 SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002815 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002816 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002817}
2818
2819/// The UsualUnaryConversions() function is *not* called by this routine.
2820/// See C99 6.3.2.1p[2-4] for more details.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002821bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2822 SourceLocation OpLoc,
2823 SourceRange ExprRange,
2824 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl28507842009-02-26 14:39:58 +00002825 if (exprType->isDependentType())
2826 return false;
2827
Sebastian Redl5d484e82009-11-23 17:18:46 +00002828 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2829 // the result is the size of the referenced type."
2830 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2831 // result shall be the alignment of the referenced type."
2832 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2833 exprType = Ref->getPointeeType();
2834
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002835 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2836 // scalar or vector data type argument..."
2837 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2838 // type (C99 6.2.5p18) or void.
2839 if (ExprKind == UETT_VecStep) {
2840 if (!(exprType->isArithmeticType() || exprType->isVoidType() ||
2841 exprType->isVectorType())) {
2842 Diag(OpLoc, diag::err_vecstep_non_scalar_vector_type)
2843 << exprType << ExprRange;
2844 return true;
2845 }
2846 }
2847
Reid Spencer5f016e22007-07-11 17:01:13 +00002848 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00002849 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002850 // alignof(function) is allowed as an extension.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002851 if (ExprKind == UETT_SizeOf)
2852 Diag(OpLoc, diag::ext_sizeof_function_type)
2853 << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00002854 return false;
2855 }
Mike Stump1eb44332009-09-09 15:08:12 +00002856
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002857 // Allow sizeof(void)/alignof(void) as an extension. vec_step(void) is not
2858 // an extension, as void is a built-in scalar type (OpenCL 1.1 6.1.1).
Chris Lattner01072922009-01-24 19:46:37 +00002859 if (exprType->isVoidType()) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002860 if (ExprKind != UETT_VecStep)
2861 Diag(OpLoc, diag::ext_sizeof_void_type)
2862 << ExprKind << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00002863 return false;
2864 }
Mike Stump1eb44332009-09-09 15:08:12 +00002865
Chris Lattner1efaa952009-04-24 00:30:45 +00002866 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002867 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002868 << ExprKind << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002869 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002870
Chris Lattner1efaa952009-04-24 00:30:45 +00002871 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCallc12c5bb2010-05-15 11:32:37 +00002872 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002873 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002874 << exprType << (ExprKind == UETT_SizeOf)
2875 << ExprRange;
Chris Lattner5cb10d32009-04-24 22:30:50 +00002876 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00002877 }
Mike Stump1eb44332009-09-09 15:08:12 +00002878
Chris Lattner1efaa952009-04-24 00:30:45 +00002879 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002880}
2881
John McCall2a984ca2010-10-12 00:20:44 +00002882static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2883 SourceRange ExprRange) {
Chris Lattner31e21e02009-01-24 20:17:12 +00002884 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002885
Mike Stump1eb44332009-09-09 15:08:12 +00002886 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002887 if (isa<DeclRefExpr>(E))
2888 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002889
2890 // Cannot know anything else if the expression is dependent.
2891 if (E->isTypeDependent())
2892 return false;
2893
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002894 if (E->getBitField()) {
John McCall2a984ca2010-10-12 00:20:44 +00002895 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002896 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002897 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002898
2899 // Alignment of a field access is always okay, so long as it isn't a
2900 // bit-field.
2901 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002902 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002903 return false;
2904
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002905 return S.CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
2906 UETT_AlignOf);
2907}
2908
2909bool Sema::CheckVecStepExpr(Expr *E, SourceLocation OpLoc,
2910 SourceRange ExprRange) {
2911 E = E->IgnoreParens();
2912
2913 // Cannot know anything else if the expression is dependent.
2914 if (E->isTypeDependent())
2915 return false;
2916
2917 return CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
2918 UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00002919}
2920
Douglas Gregorba498172009-03-13 21:01:28 +00002921/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002922ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002923Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2924 SourceLocation OpLoc,
2925 UnaryExprOrTypeTrait ExprKind,
2926 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002927 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002928 return ExprError();
2929
John McCalla93c9342009-12-07 02:54:59 +00002930 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002931
Douglas Gregorba498172009-03-13 21:01:28 +00002932 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002933 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00002934 return ExprError();
2935
2936 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002937 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2938 Context.getSizeType(),
2939 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002940}
2941
2942/// \brief Build a sizeof or alignof expression given an expression
2943/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002944ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002945Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2946 UnaryExprOrTypeTrait ExprKind,
2947 SourceRange R) {
Douglas Gregorba498172009-03-13 21:01:28 +00002948 // Verify that the operand is valid.
2949 bool isInvalid = false;
2950 if (E->isTypeDependent()) {
2951 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002952 } else if (ExprKind == UETT_AlignOf) {
John McCall2a984ca2010-10-12 00:20:44 +00002953 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002954 } else if (ExprKind == UETT_VecStep) {
2955 isInvalid = CheckVecStepExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002956 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00002957 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2958 isInvalid = true;
John McCall2cd11fe2010-10-12 02:09:17 +00002959 } else if (E->getType()->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00002960 ExprResult PE = CheckPlaceholderExpr(E);
John McCall2cd11fe2010-10-12 02:09:17 +00002961 if (PE.isInvalid()) return ExprError();
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002962 return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind, R);
Douglas Gregorba498172009-03-13 21:01:28 +00002963 } else {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002964 isInvalid = CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, R,
2965 UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00002966 }
2967
2968 if (isInvalid)
2969 return ExprError();
2970
2971 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002972 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, E,
2973 Context.getSizeType(),
2974 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002975}
2976
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002977/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2978/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00002979/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00002980ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002981Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2982 UnaryExprOrTypeTrait ExprKind, bool isType,
2983 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002984 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002985 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002986
Sebastian Redl05189992008-11-11 17:56:53 +00002987 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00002988 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00002989 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002990 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002991 }
Sebastian Redl05189992008-11-11 17:56:53 +00002992
Douglas Gregorba498172009-03-13 21:01:28 +00002993 Expr *ArgEx = (Expr *)TyOrEx;
John McCall60d7b3a2010-08-24 06:29:42 +00002994 ExprResult Result
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002995 = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind,
2996 ArgEx->getSourceRange());
Douglas Gregorba498172009-03-13 21:01:28 +00002997
Douglas Gregorba498172009-03-13 21:01:28 +00002998 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002999}
3000
John Wiegley429bb272011-04-08 18:41:53 +00003001static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall09431682010-11-18 19:01:18 +00003002 bool isReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003003 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003004 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003005
John McCallf6a16482010-12-04 03:47:34 +00003006 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003007 if (V.get()->getObjectKind() != OK_Ordinary) {
3008 V = S.DefaultLvalueConversion(V.take());
3009 if (V.isInvalid())
3010 return QualType();
3011 }
John McCallf6a16482010-12-04 03:47:34 +00003012
Chris Lattnercc26ed72007-08-26 05:39:26 +00003013 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003014 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003015 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003016
Chris Lattnercc26ed72007-08-26 05:39:26 +00003017 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003018 if (V.get()->getType()->isArithmeticType())
3019 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003020
John McCall2cd11fe2010-10-12 02:09:17 +00003021 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003022 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003023 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003024 if (PR.get() != V.get()) {
3025 V = move(PR);
John McCall09431682010-11-18 19:01:18 +00003026 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003027 }
3028
Chris Lattnercc26ed72007-08-26 05:39:26 +00003029 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003030 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattnerba27e2a2009-02-17 08:12:06 +00003031 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003032 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003033}
3034
3035
Reid Spencer5f016e22007-07-11 17:01:13 +00003036
John McCall60d7b3a2010-08-24 06:29:42 +00003037ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003038Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003039 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003040 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003041 switch (Kind) {
3042 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003043 case tok::plusplus: Opc = UO_PostInc; break;
3044 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003045 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003046
John McCall9ae2f072010-08-23 23:25:46 +00003047 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003048}
3049
John McCall09431682010-11-18 19:01:18 +00003050/// Expressions of certain arbitrary types are forbidden by C from
3051/// having l-value type. These are:
3052/// - 'void', but not qualified void
3053/// - function types
3054///
3055/// The exact rule here is C99 6.3.2.1:
3056/// An lvalue is an expression with an object type or an incomplete
3057/// type other than void.
3058static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
3059 return ((T->isVoidType() && !T.hasQualifiers()) ||
3060 T->isFunctionType());
3061}
3062
John McCall60d7b3a2010-08-24 06:29:42 +00003063ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003064Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3065 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003066 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003067 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003068 if (Result.isInvalid()) return ExprError();
3069 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003070
John McCall9ae2f072010-08-23 23:25:46 +00003071 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003072
Douglas Gregor337c6b92008-11-19 17:17:41 +00003073 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003074 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003075 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003076 Context.DependentTy,
3077 VK_LValue, OK_Ordinary,
3078 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003079 }
3080
Mike Stump1eb44332009-09-09 15:08:12 +00003081 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003082 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003083 LHSExp->getType()->isEnumeralType() ||
3084 RHSExp->getType()->isRecordType() ||
3085 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00003086 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003087 }
3088
John McCall9ae2f072010-08-23 23:25:46 +00003089 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003090}
3091
3092
John McCall60d7b3a2010-08-24 06:29:42 +00003093ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003094Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3095 Expr *Idx, SourceLocation RLoc) {
3096 Expr *LHSExp = Base;
3097 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003098
Chris Lattner12d9ff62007-07-16 00:14:47 +00003099 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003100 if (!LHSExp->getType()->getAs<VectorType>()) {
3101 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3102 if (Result.isInvalid())
3103 return ExprError();
3104 LHSExp = Result.take();
3105 }
3106 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3107 if (Result.isInvalid())
3108 return ExprError();
3109 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003110
Chris Lattner12d9ff62007-07-16 00:14:47 +00003111 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003112 ExprValueKind VK = VK_LValue;
3113 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003114
Reid Spencer5f016e22007-07-11 17:01:13 +00003115 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003116 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003117 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003118 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003119 Expr *BaseExpr, *IndexExpr;
3120 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003121 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3122 BaseExpr = LHSExp;
3123 IndexExpr = RHSExp;
3124 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003125 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003126 BaseExpr = LHSExp;
3127 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003128 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003129 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00003130 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00003131 BaseExpr = RHSExp;
3132 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003133 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003134 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003135 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003136 BaseExpr = LHSExp;
3137 IndexExpr = RHSExp;
3138 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003139 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003140 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003141 // Handle the uncommon case of "123[Ptr]".
3142 BaseExpr = RHSExp;
3143 IndexExpr = LHSExp;
3144 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003145 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003146 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003147 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003148 VK = LHSExp->getValueKind();
3149 if (VK != VK_RValue)
3150 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003151
Chris Lattner12d9ff62007-07-16 00:14:47 +00003152 // FIXME: need to deal with const...
3153 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003154 } else if (LHSTy->isArrayType()) {
3155 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003156 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003157 // wasn't promoted because of the C90 rule that doesn't
3158 // allow promoting non-lvalue arrays. Warn, then
3159 // force the promotion here.
3160 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3161 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003162 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3163 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003164 LHSTy = LHSExp->getType();
3165
3166 BaseExpr = LHSExp;
3167 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003168 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003169 } else if (RHSTy->isArrayType()) {
3170 // Same as previous, except for 123[f().a] case
3171 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3172 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003173 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3174 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003175 RHSTy = RHSExp->getType();
3176
3177 BaseExpr = RHSExp;
3178 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003179 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003180 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003181 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3182 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003183 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003184 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003185 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003186 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3187 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003188
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003189 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003190 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3191 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003192 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3193
Douglas Gregore7450f52009-03-24 19:52:54 +00003194 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003195 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3196 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003197 // incomplete types are not object types.
3198 if (ResultType->isFunctionType()) {
3199 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3200 << ResultType << BaseExpr->getSourceRange();
3201 return ExprError();
3202 }
Mike Stump1eb44332009-09-09 15:08:12 +00003203
Abramo Bagnara46358452010-09-13 06:50:07 +00003204 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3205 // GNU extension: subscripting on pointer to void
3206 Diag(LLoc, diag::ext_gnu_void_ptr)
3207 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003208
3209 // C forbids expressions of unqualified void type from being l-values.
3210 // See IsCForbiddenLValueType.
3211 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003212 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003213 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003214 PDiag(diag::err_subscript_incomplete_type)
3215 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003216 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003217
Chris Lattner1efaa952009-04-24 00:30:45 +00003218 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003219 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003220 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3221 << ResultType << BaseExpr->getSourceRange();
3222 return ExprError();
3223 }
Mike Stump1eb44332009-09-09 15:08:12 +00003224
John McCall09431682010-11-18 19:01:18 +00003225 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3226 !IsCForbiddenLValueType(Context, ResultType));
3227
Mike Stumpeed9cac2009-02-19 03:04:26 +00003228 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003229 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003230}
3231
John McCall09431682010-11-18 19:01:18 +00003232/// Check an ext-vector component access expression.
3233///
3234/// VK should be set in advance to the value kind of the base
3235/// expression.
3236static QualType
3237CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3238 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003239 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00003240 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3241 // see FIXME there.
3242 //
3243 // FIXME: This logic can be greatly simplified by splitting it along
3244 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00003245 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00003246
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003247 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00003248 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003249
Mike Stumpeed9cac2009-02-19 03:04:26 +00003250 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00003251 // special names that indicate a subset of exactly half the elements are
3252 // to be selected.
3253 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003254
Nate Begeman353417a2009-01-18 01:47:54 +00003255 // This flag determines whether or not CompName has an 's' char prefix,
3256 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00003257 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00003258
John McCall09431682010-11-18 19:01:18 +00003259 bool HasRepeated = false;
3260 bool HasIndex[16] = {};
3261
3262 int Idx;
3263
Nate Begeman8a997642008-05-09 06:41:27 +00003264 // Check that we've found one of the special components, or that the component
3265 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003266 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00003267 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3268 HalvingSwizzle = true;
John McCall09431682010-11-18 19:01:18 +00003269 } else if (!HexSwizzle &&
3270 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3271 do {
3272 if (HasIndex[Idx]) HasRepeated = true;
3273 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003274 compStr++;
John McCall09431682010-11-18 19:01:18 +00003275 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3276 } else {
3277 if (HexSwizzle) compStr++;
3278 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3279 if (HasIndex[Idx]) HasRepeated = true;
3280 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003281 compStr++;
John McCall09431682010-11-18 19:01:18 +00003282 }
Chris Lattner88dca042007-08-02 22:33:49 +00003283 }
Nate Begeman353417a2009-01-18 01:47:54 +00003284
Mike Stumpeed9cac2009-02-19 03:04:26 +00003285 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003286 // We didn't get to the end of the string. This means the component names
3287 // didn't come from the same set *or* we encountered an illegal name.
John McCall09431682010-11-18 19:01:18 +00003288 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00003289 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003290 return QualType();
3291 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003292
Nate Begeman353417a2009-01-18 01:47:54 +00003293 // Ensure no component accessor exceeds the width of the vector type it
3294 // operates on.
3295 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00003296 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003297
3298 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003299 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00003300
3301 while (*compStr) {
3302 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall09431682010-11-18 19:01:18 +00003303 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begeman353417a2009-01-18 01:47:54 +00003304 << baseType << SourceRange(CompLoc);
3305 return QualType();
3306 }
3307 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003308 }
Nate Begeman8a997642008-05-09 06:41:27 +00003309
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003310 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003311 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003312 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00003313 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00003314 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00003315 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00003316 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00003317 if (HexSwizzle)
3318 CompSize--;
3319
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003320 if (CompSize == 1)
3321 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003322
John McCall09431682010-11-18 19:01:18 +00003323 if (HasRepeated) VK = VK_RValue;
3324
3325 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003326 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00003327 // diagostics look bad. We want extended vector types to appear built-in.
John McCall09431682010-11-18 19:01:18 +00003328 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3329 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3330 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00003331 }
3332 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003333}
3334
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003335static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003336 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003337 const Selector &Sel,
3338 ASTContext &Context) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003339 if (Member)
3340 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3341 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003342 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003343 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00003344
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003345 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3346 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003347 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3348 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003349 return D;
3350 }
3351 return 0;
3352}
3353
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003354static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3355 IdentifierInfo *Member,
3356 const Selector &Sel,
3357 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003358 // Check protocols on qualified interfaces.
3359 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003360 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003361 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003362 if (Member)
3363 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3364 GDecl = PD;
3365 break;
3366 }
3367 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003368 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003369 GDecl = OMD;
3370 break;
3371 }
3372 }
3373 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003374 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003375 E = QIdTy->qual_end(); I != E; ++I) {
3376 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003377 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3378 Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003379 if (GDecl)
3380 return GDecl;
3381 }
3382 }
3383 return GDecl;
3384}
Chris Lattner76a642f2009-02-15 22:43:40 +00003385
John McCall60d7b3a2010-08-24 06:29:42 +00003386ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003387Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCallaa81e162009-12-01 22:10:20 +00003388 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00003389 const CXXScopeSpec &SS,
3390 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003391 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003392 const TemplateArgumentListInfo *TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00003393 // Even in dependent contexts, try to diagnose base expressions with
3394 // obviously wrong types, e.g.:
3395 //
3396 // T* t;
3397 // t.f;
3398 //
3399 // In Obj-C++, however, the above expression is valid, since it could be
3400 // accessing the 'f' property if T is an Obj-C interface. The extra check
3401 // allows this, while still reporting an error if T is a struct pointer.
3402 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00003403 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00003404 if (PT && (!getLangOptions().ObjC1 ||
3405 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00003406 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnara25777432010-08-11 22:01:17 +00003407 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00003408 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00003409 return ExprError();
3410 }
3411 }
3412
Abramo Bagnara25777432010-08-11 22:01:17 +00003413 assert(BaseType->isDependentType() ||
3414 NameInfo.getName().isDependentName() ||
Douglas Gregor01e56ae2010-04-12 20:54:26 +00003415 isDependentScopeSpecifier(SS));
John McCall129e2df2009-11-30 22:42:35 +00003416
3417 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3418 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00003419 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003420 IsArrow, OpLoc,
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003421 SS.getWithLocInContext(Context),
John McCall129e2df2009-11-30 22:42:35 +00003422 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003423 NameInfo, TemplateArgs));
John McCall129e2df2009-11-30 22:42:35 +00003424}
3425
3426/// We know that the given qualified member reference points only to
3427/// declarations which do not belong to the static type of the base
3428/// expression. Diagnose the problem.
3429static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3430 Expr *BaseExpr,
3431 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003432 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00003433 NamedDecl *rep,
3434 const DeclarationNameInfo &nameInfo) {
John McCall2f841ba2009-12-02 03:53:29 +00003435 // If this is an implicit member access, use a different set of
3436 // diagnostics.
3437 if (!BaseExpr)
John McCall5808ce42011-02-03 08:15:49 +00003438 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003439
John McCall5808ce42011-02-03 08:15:49 +00003440 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3441 << SS.getRange() << rep << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00003442}
3443
3444// Check whether the declarations we found through a nested-name
3445// specifier in a member expression are actually members of the base
3446// type. The restriction here is:
3447//
3448// C++ [expr.ref]p2:
3449// ... In these cases, the id-expression shall name a
3450// member of the class or of one of its base classes.
3451//
3452// So it's perfectly legitimate for the nested-name specifier to name
3453// an unrelated class, and for us to find an overload set including
3454// decls from classes which are not superclasses, as long as the decl
3455// we actually pick through overload resolution is from a superclass.
3456bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3457 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003458 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003459 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00003460 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3461 if (!BaseRT) {
3462 // We can't check this yet because the base type is still
3463 // dependent.
3464 assert(BaseType->isDependentType());
3465 return false;
3466 }
3467 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00003468
3469 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00003470 // If this is an implicit member reference and we find a
3471 // non-instance member, it's not an error.
John McCall161755a2010-04-06 21:38:20 +00003472 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00003473 return false;
John McCall129e2df2009-11-30 22:42:35 +00003474
John McCallaa81e162009-12-01 22:10:20 +00003475 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman02463762010-07-27 20:51:02 +00003476 DeclContext *DC = (*I)->getDeclContext();
3477 while (DC->isTransparentContext())
3478 DC = DC->getParent();
John McCallaa81e162009-12-01 22:10:20 +00003479
Douglas Gregor9d4bb942010-07-28 22:27:52 +00003480 if (!DC->isRecord())
3481 continue;
3482
John McCallaa81e162009-12-01 22:10:20 +00003483 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman02463762010-07-27 20:51:02 +00003484 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCallaa81e162009-12-01 22:10:20 +00003485
3486 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3487 return false;
3488 }
3489
John McCall5808ce42011-02-03 08:15:49 +00003490 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3491 R.getRepresentativeDecl(),
3492 R.getLookupNameInfo());
John McCallaa81e162009-12-01 22:10:20 +00003493 return true;
3494}
3495
3496static bool
3497LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3498 SourceRange BaseRange, const RecordType *RTy,
John McCallad00b772010-06-16 08:42:20 +00003499 SourceLocation OpLoc, CXXScopeSpec &SS,
3500 bool HasTemplateArgs) {
John McCallaa81e162009-12-01 22:10:20 +00003501 RecordDecl *RDecl = RTy->getDecl();
3502 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003503 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCallaa81e162009-12-01 22:10:20 +00003504 << BaseRange))
3505 return true;
3506
John McCallad00b772010-06-16 08:42:20 +00003507 if (HasTemplateArgs) {
3508 // LookupTemplateName doesn't expect these both to exist simultaneously.
3509 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3510
3511 bool MOUS;
3512 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3513 return false;
3514 }
3515
John McCallaa81e162009-12-01 22:10:20 +00003516 DeclContext *DC = RDecl;
3517 if (SS.isSet()) {
3518 // If the member name was a qualified-id, look into the
3519 // nested-name-specifier.
3520 DC = SemaRef.computeDeclContext(SS, false);
3521
John McCall77bb1aa2010-05-01 00:40:08 +00003522 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCall2f841ba2009-12-02 03:53:29 +00003523 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3524 << SS.getRange() << DC;
3525 return true;
3526 }
3527
John McCallaa81e162009-12-01 22:10:20 +00003528 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003529
John McCallaa81e162009-12-01 22:10:20 +00003530 if (!isa<TypeDecl>(DC)) {
3531 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3532 << DC << SS.getRange();
3533 return true;
John McCall129e2df2009-11-30 22:42:35 +00003534 }
3535 }
3536
John McCallaa81e162009-12-01 22:10:20 +00003537 // The record definition is complete, now look up the member.
3538 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00003539
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003540 if (!R.empty())
3541 return false;
3542
3543 // We didn't find anything with the given name, so try to correct
3544 // for typos.
3545 DeclarationName Name = R.getLookupName();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003546 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00003547 !R.empty() &&
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003548 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3549 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3550 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003551 << FixItHint::CreateReplacement(R.getNameLoc(),
3552 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003553 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3554 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3555 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003556 return false;
3557 } else {
3558 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003559 R.setLookupName(Name);
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003560 }
3561
John McCall129e2df2009-11-30 22:42:35 +00003562 return false;
3563}
3564
John McCall60d7b3a2010-08-24 06:29:42 +00003565ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003566Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003567 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003568 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003569 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003570 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003571 const TemplateArgumentListInfo *TemplateArgs) {
John McCall2f841ba2009-12-02 03:53:29 +00003572 if (BaseType->isDependentType() ||
3573 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall9ae2f072010-08-23 23:25:46 +00003574 return ActOnDependentMemberExpr(Base, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003575 IsArrow, OpLoc,
3576 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003577 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003578
Abramo Bagnara25777432010-08-11 22:01:17 +00003579 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00003580
John McCallaa81e162009-12-01 22:10:20 +00003581 // Implicit member accesses.
3582 if (!Base) {
3583 QualType RecordTy = BaseType;
3584 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3585 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3586 RecordTy->getAs<RecordType>(),
John McCallad00b772010-06-16 08:42:20 +00003587 OpLoc, SS, TemplateArgs != 0))
John McCallaa81e162009-12-01 22:10:20 +00003588 return ExprError();
3589
3590 // Explicit member accesses.
3591 } else {
John Wiegley429bb272011-04-08 18:41:53 +00003592 ExprResult BaseResult = Owned(Base);
John McCall60d7b3a2010-08-24 06:29:42 +00003593 ExprResult Result =
John Wiegley429bb272011-04-08 18:41:53 +00003594 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCalld226f652010-08-21 09:40:31 +00003595 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCallaa81e162009-12-01 22:10:20 +00003596
John Wiegley429bb272011-04-08 18:41:53 +00003597 if (BaseResult.isInvalid())
3598 return ExprError();
3599 Base = BaseResult.take();
3600
John McCallaa81e162009-12-01 22:10:20 +00003601 if (Result.isInvalid()) {
3602 Owned(Base);
3603 return ExprError();
3604 }
3605
3606 if (Result.get())
3607 return move(Result);
Sebastian Redlf3e63372010-05-07 09:25:11 +00003608
3609 // LookupMemberExpr can modify Base, and thus change BaseType
3610 BaseType = Base->getType();
John McCall129e2df2009-11-30 22:42:35 +00003611 }
3612
John McCall9ae2f072010-08-23 23:25:46 +00003613 return BuildMemberReferenceExpr(Base, BaseType,
John McCallc2233c52010-01-15 08:34:02 +00003614 OpLoc, IsArrow, SS, FirstQualifierInScope,
3615 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003616}
3617
John McCall60d7b3a2010-08-24 06:29:42 +00003618ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003619Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCallaa81e162009-12-01 22:10:20 +00003620 SourceLocation OpLoc, bool IsArrow,
3621 const CXXScopeSpec &SS,
John McCallc2233c52010-01-15 08:34:02 +00003622 NamedDecl *FirstQualifierInScope,
John McCall129e2df2009-11-30 22:42:35 +00003623 LookupResult &R,
Douglas Gregor06a9f362010-05-01 20:49:11 +00003624 const TemplateArgumentListInfo *TemplateArgs,
3625 bool SuppressQualifierCheck) {
John McCallaa81e162009-12-01 22:10:20 +00003626 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00003627 if (IsArrow) {
3628 assert(BaseType->isPointerType());
3629 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3630 }
John McCall161755a2010-04-06 21:38:20 +00003631 R.setBaseObjectType(BaseType);
John McCall129e2df2009-11-30 22:42:35 +00003632
Abramo Bagnara25777432010-08-11 22:01:17 +00003633 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3634 DeclarationName MemberName = MemberNameInfo.getName();
3635 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall129e2df2009-11-30 22:42:35 +00003636
3637 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00003638 return ExprError();
3639
John McCall129e2df2009-11-30 22:42:35 +00003640 if (R.empty()) {
3641 // Rederive where we looked up.
3642 DeclContext *DC = (SS.isSet()
3643 ? computeDeclContext(SS, false)
3644 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00003645
John McCall129e2df2009-11-30 22:42:35 +00003646 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00003647 << MemberName << DC
3648 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00003649 return ExprError();
3650 }
3651
John McCallc2233c52010-01-15 08:34:02 +00003652 // Diagnose lookups that find only declarations from a non-base
3653 // type. This is possible for either qualified lookups (which may
3654 // have been qualified with an unrelated type) or implicit member
3655 // expressions (which were found with unqualified lookup and thus
3656 // may have come from an enclosing scope). Note that it's okay for
3657 // lookup to find declarations from a non-base type as long as those
3658 // aren't the ones picked by overload resolution.
3659 if ((SS.isSet() || !BaseExpr ||
3660 (isa<CXXThisExpr>(BaseExpr) &&
3661 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00003662 !SuppressQualifierCheck &&
John McCallc2233c52010-01-15 08:34:02 +00003663 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00003664 return ExprError();
3665
3666 // Construct an unresolved result if we in fact got an unresolved
3667 // result.
3668 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallc373d482010-01-27 01:50:18 +00003669 // Suppress any lookup-related diagnostics; we'll do these when we
3670 // pick a member.
3671 R.suppressDiagnostics();
3672
John McCall129e2df2009-11-30 22:42:35 +00003673 UnresolvedMemberExpr *MemExpr
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003674 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00003675 BaseExpr, BaseExprType,
3676 IsArrow, OpLoc,
Douglas Gregor4c9be892011-02-28 20:01:57 +00003677 SS.getWithLocInContext(Context),
Abramo Bagnara25777432010-08-11 22:01:17 +00003678 MemberNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00003679 TemplateArgs, R.begin(), R.end());
John McCall129e2df2009-11-30 22:42:35 +00003680
3681 return Owned(MemExpr);
3682 }
3683
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003684 assert(R.isSingleResult());
John McCall161755a2010-04-06 21:38:20 +00003685 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall129e2df2009-11-30 22:42:35 +00003686 NamedDecl *MemberDecl = R.getFoundDecl();
3687
3688 // FIXME: diagnose the presence of template arguments now.
3689
3690 // If the decl being referenced had an error, return an error for this
3691 // sub-expr without emitting another error, in order to avoid cascading
3692 // error cases.
3693 if (MemberDecl->isInvalidDecl())
3694 return ExprError();
3695
John McCallaa81e162009-12-01 22:10:20 +00003696 // Handle the implicit-member-access case.
3697 if (!BaseExpr) {
3698 // If this is not an instance member, convert to a non-member access.
John McCall161755a2010-04-06 21:38:20 +00003699 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnara25777432010-08-11 22:01:17 +00003700 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCallaa81e162009-12-01 22:10:20 +00003701
Douglas Gregor828a1972010-01-07 23:12:05 +00003702 SourceLocation Loc = R.getNameLoc();
3703 if (SS.getRange().isValid())
3704 Loc = SS.getRange().getBegin();
3705 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003706 }
3707
John McCall129e2df2009-11-30 22:42:35 +00003708 bool ShouldCheckUse = true;
3709 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3710 // Don't diagnose the use of a virtual member function unless it's
3711 // explicitly qualified.
3712 if (MD->isVirtual() && !SS.isSet())
3713 ShouldCheckUse = false;
3714 }
3715
3716 // Check the use of this member.
3717 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3718 Owned(BaseExpr);
3719 return ExprError();
3720 }
3721
John McCallf6a16482010-12-04 03:47:34 +00003722 // Perform a property load on the base regardless of whether we
3723 // actually need it for the declaration.
John Wiegley429bb272011-04-08 18:41:53 +00003724 if (BaseExpr->getObjectKind() == OK_ObjCProperty) {
3725 ExprResult Result = ConvertPropertyForRValue(BaseExpr);
3726 if (Result.isInvalid())
3727 return ExprError();
3728 BaseExpr = Result.take();
3729 }
John McCallf6a16482010-12-04 03:47:34 +00003730
John McCalldfa1edb2010-11-23 20:48:44 +00003731 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3732 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3733 SS, FD, FoundDecl, MemberNameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003734
Francois Pichet87c2e122010-11-21 06:08:52 +00003735 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3736 // We may have found a field within an anonymous union or struct
3737 // (C++ [class.union]).
John McCall5808ce42011-02-03 08:15:49 +00003738 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCallf6a16482010-12-04 03:47:34 +00003739 BaseExpr, OpLoc);
Francois Pichet87c2e122010-11-21 06:08:52 +00003740
John McCall129e2df2009-11-30 22:42:35 +00003741 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3742 MarkDeclarationReferenced(MemberLoc, Var);
3743 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003744 Var, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003745 Var->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00003746 VK_LValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003747 }
3748
John McCallf89e55a2010-11-18 06:31:45 +00003749 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall129e2df2009-11-30 22:42:35 +00003750 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3751 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003752 MemberFn, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003753 MemberFn->getType(),
3754 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3755 OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003756 }
John McCallf89e55a2010-11-18 06:31:45 +00003757 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall129e2df2009-11-30 22:42:35 +00003758
3759 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3760 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3761 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003762 Enum, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003763 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003764 }
3765
3766 Owned(BaseExpr);
3767
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003768 // We found something that we didn't expect. Complain.
John McCall129e2df2009-11-30 22:42:35 +00003769 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnara25777432010-08-11 22:01:17 +00003770 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003771 << MemberName << BaseType << int(IsArrow);
3772 else
3773 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3774 << MemberName << BaseType << int(IsArrow);
John McCall129e2df2009-11-30 22:42:35 +00003775
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003776 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3777 << MemberName;
Douglas Gregor2b147f02010-04-25 21:15:30 +00003778 R.suppressDiagnostics();
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003779 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00003780}
3781
John McCall028d3972010-12-15 16:46:44 +00003782/// Given that normal member access failed on the given expression,
3783/// and given that the expression's type involves builtin-id or
3784/// builtin-Class, decide whether substituting in the redefinition
3785/// types would be profitable. The redefinition type is whatever
3786/// this translation unit tried to typedef to id/Class; we store
3787/// it to the side and then re-use it in places like this.
John Wiegley429bb272011-04-08 18:41:53 +00003788static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
John McCall028d3972010-12-15 16:46:44 +00003789 const ObjCObjectPointerType *opty
John Wiegley429bb272011-04-08 18:41:53 +00003790 = base.get()->getType()->getAs<ObjCObjectPointerType>();
John McCall028d3972010-12-15 16:46:44 +00003791 if (!opty) return false;
3792
3793 const ObjCObjectType *ty = opty->getObjectType();
3794
3795 QualType redef;
3796 if (ty->isObjCId()) {
3797 redef = S.Context.ObjCIdRedefinitionType;
3798 } else if (ty->isObjCClass()) {
3799 redef = S.Context.ObjCClassRedefinitionType;
3800 } else {
3801 return false;
3802 }
3803
3804 // Do the substitution as long as the redefinition type isn't just a
3805 // possibly-qualified pointer to builtin-id or builtin-Class again.
3806 opty = redef->getAs<ObjCObjectPointerType>();
3807 if (opty && !opty->getObjectType()->getInterface() != 0)
3808 return false;
3809
John Wiegley429bb272011-04-08 18:41:53 +00003810 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
John McCall028d3972010-12-15 16:46:44 +00003811 return true;
3812}
3813
John McCall129e2df2009-11-30 22:42:35 +00003814/// Look up the given member of the given non-type-dependent
3815/// expression. This can return in one of two ways:
3816/// * If it returns a sentinel null-but-valid result, the caller will
3817/// assume that lookup was performed and the results written into
3818/// the provided structure. It will take over from there.
3819/// * Otherwise, the returned expression will be produced in place of
3820/// an ordinary member expression.
3821///
3822/// The ObjCImpDecl bit is a gross hack that will need to be properly
3823/// fixed for ObjC++.
John McCall60d7b3a2010-08-24 06:29:42 +00003824ExprResult
John Wiegley429bb272011-04-08 18:41:53 +00003825Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00003826 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003827 CXXScopeSpec &SS,
John McCalld226f652010-08-21 09:40:31 +00003828 Decl *ObjCImpDecl, bool HasTemplateArgs) {
John Wiegley429bb272011-04-08 18:41:53 +00003829 assert(BaseExpr.get() && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003830
Steve Naroff3cc4af82007-12-16 21:42:28 +00003831 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003832 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003833
John Wiegley429bb272011-04-08 18:41:53 +00003834 if (IsArrow) {
3835 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
3836 if (BaseExpr.isInvalid())
3837 return ExprError();
3838 }
3839
3840 QualType BaseType = BaseExpr.get()->getType();
John McCall129e2df2009-11-30 22:42:35 +00003841 assert(!BaseType->isDependentType());
3842
3843 DeclarationName MemberName = R.getLookupName();
3844 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00003845
John McCall028d3972010-12-15 16:46:44 +00003846 // For later type-checking purposes, turn arrow accesses into dot
3847 // accesses. The only access type we support that doesn't follow
3848 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3849 // and those never use arrows, so this is unaffected.
3850 if (IsArrow) {
3851 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3852 BaseType = Ptr->getPointeeType();
3853 else if (const ObjCObjectPointerType *Ptr
3854 = BaseType->getAs<ObjCObjectPointerType>())
3855 BaseType = Ptr->getPointeeType();
3856 else if (BaseType->isRecordType()) {
3857 // Recover from arrow accesses to records, e.g.:
3858 // struct MyRecord foo;
3859 // foo->bar
3860 // This is actually well-formed in C++ if MyRecord has an
3861 // overloaded operator->, but that should have been dealt with
3862 // by now.
3863 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley429bb272011-04-08 18:41:53 +00003864 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
John McCall028d3972010-12-15 16:46:44 +00003865 << FixItHint::CreateReplacement(OpLoc, ".");
3866 IsArrow = false;
3867 } else {
3868 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
John Wiegley429bb272011-04-08 18:41:53 +00003869 << BaseType << BaseExpr.get()->getSourceRange();
John McCall028d3972010-12-15 16:46:44 +00003870 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00003871 }
3872 }
3873
John McCall028d3972010-12-15 16:46:44 +00003874 // Handle field access to simple records.
3875 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John Wiegley429bb272011-04-08 18:41:53 +00003876 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
John McCall028d3972010-12-15 16:46:44 +00003877 RTy, OpLoc, SS, HasTemplateArgs))
3878 return ExprError();
3879
3880 // Returning valid-but-null is how we indicate to the caller that
3881 // the lookup result was filled in.
3882 return Owned((Expr*) 0);
David Chisnall0f436562009-08-17 16:35:33 +00003883 }
John McCall129e2df2009-11-30 22:42:35 +00003884
John McCall028d3972010-12-15 16:46:44 +00003885 // Handle ivar access to Objective-C objects.
3886 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003887 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall028d3972010-12-15 16:46:44 +00003888
3889 // There are three cases for the base type:
3890 // - builtin id (qualified or unqualified)
3891 // - builtin Class (qualified or unqualified)
3892 // - an interface
3893 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3894 if (!IDecl) {
3895 // There's an implicit 'isa' ivar on all objects.
3896 // But we only actually find it this way on objects of type 'id',
3897 // apparently.
3898 if (OTy->isObjCId() && Member->isStr("isa"))
John Wiegley429bb272011-04-08 18:41:53 +00003899 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
John McCall028d3972010-12-15 16:46:44 +00003900 Context.getObjCClassType()));
3901
3902 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3903 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3904 ObjCImpDecl, HasTemplateArgs);
3905 goto fail;
3906 }
3907
3908 ObjCInterfaceDecl *ClassDeclared;
3909 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3910
3911 if (!IV) {
3912 // Attempt to correct for typos in ivar names.
3913 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3914 LookupMemberName);
3915 if (CorrectTypo(Res, 0, 0, IDecl, false,
3916 IsArrow ? CTC_ObjCIvarLookup
3917 : CTC_ObjCPropertyLookup) &&
3918 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3919 Diag(R.getNameLoc(),
3920 diag::err_typecheck_member_reference_ivar_suggest)
3921 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3922 << FixItHint::CreateReplacement(R.getNameLoc(),
3923 IV->getNameAsString());
3924 Diag(IV->getLocation(), diag::note_previous_decl)
3925 << IV->getDeclName();
3926 } else {
3927 Res.clear();
3928 Res.setLookupName(Member);
3929
3930 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3931 << IDecl->getDeclName() << MemberName
John Wiegley429bb272011-04-08 18:41:53 +00003932 << BaseExpr.get()->getSourceRange();
John McCall028d3972010-12-15 16:46:44 +00003933 return ExprError();
3934 }
3935 }
3936
3937 // If the decl being referenced had an error, return an error for this
3938 // sub-expr without emitting another error, in order to avoid cascading
3939 // error cases.
3940 if (IV->isInvalidDecl())
3941 return ExprError();
3942
3943 // Check whether we can reference this field.
3944 if (DiagnoseUseOfDecl(IV, MemberLoc))
3945 return ExprError();
3946 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3947 IV->getAccessControl() != ObjCIvarDecl::Package) {
3948 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3949 if (ObjCMethodDecl *MD = getCurMethodDecl())
3950 ClassOfMethodDecl = MD->getClassInterface();
3951 else if (ObjCImpDecl && getCurFunctionDecl()) {
3952 // Case of a c-function declared inside an objc implementation.
3953 // FIXME: For a c-style function nested inside an objc implementation
3954 // class, there is no implementation context available, so we pass
3955 // down the context as argument to this routine. Ideally, this context
3956 // need be passed down in the AST node and somehow calculated from the
3957 // AST for a function decl.
3958 if (ObjCImplementationDecl *IMPD =
3959 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3960 ClassOfMethodDecl = IMPD->getClassInterface();
3961 else if (ObjCCategoryImplDecl* CatImplClass =
3962 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3963 ClassOfMethodDecl = CatImplClass->getClassInterface();
3964 }
3965
3966 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3967 if (ClassDeclared != IDecl ||
3968 ClassOfMethodDecl != ClassDeclared)
3969 Diag(MemberLoc, diag::error_private_ivar_access)
3970 << IV->getDeclName();
3971 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3972 // @protected
3973 Diag(MemberLoc, diag::error_protected_ivar_access)
3974 << IV->getDeclName();
3975 }
3976
3977 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
John Wiegley429bb272011-04-08 18:41:53 +00003978 MemberLoc, BaseExpr.take(),
John McCall028d3972010-12-15 16:46:44 +00003979 IsArrow));
3980 }
3981
3982 // Objective-C property access.
3983 const ObjCObjectPointerType *OPT;
3984 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3985 // This actually uses the base as an r-value.
John Wiegley429bb272011-04-08 18:41:53 +00003986 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
3987 if (BaseExpr.isInvalid())
3988 return ExprError();
3989
3990 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
John McCall028d3972010-12-15 16:46:44 +00003991
3992 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3993
3994 const ObjCObjectType *OT = OPT->getObjectType();
3995
3996 // id, with and without qualifiers.
3997 if (OT->isObjCId()) {
3998 // Check protocols on qualified interfaces.
3999 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
4000 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
4001 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
4002 // Check the use of this declaration
4003 if (DiagnoseUseOfDecl(PD, MemberLoc))
4004 return ExprError();
4005
4006 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
4007 VK_LValue,
4008 OK_ObjCProperty,
4009 MemberLoc,
John Wiegley429bb272011-04-08 18:41:53 +00004010 BaseExpr.take()));
John McCall028d3972010-12-15 16:46:44 +00004011 }
4012
4013 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
4014 // Check the use of this method.
4015 if (DiagnoseUseOfDecl(OMD, MemberLoc))
4016 return ExprError();
4017 Selector SetterSel =
4018 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4019 PP.getSelectorTable(), Member);
4020 ObjCMethodDecl *SMD = 0;
4021 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
4022 SetterSel, Context))
4023 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
4024 QualType PType = OMD->getSendResultType();
4025
4026 ExprValueKind VK = VK_LValue;
4027 if (!getLangOptions().CPlusPlus &&
4028 IsCForbiddenLValueType(Context, PType))
4029 VK = VK_RValue;
4030 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4031
4032 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
4033 VK, OK,
John Wiegley429bb272011-04-08 18:41:53 +00004034 MemberLoc, BaseExpr.take()));
John McCall028d3972010-12-15 16:46:44 +00004035 }
4036 }
Fariborz Jahanian4eb7f692011-03-15 17:27:48 +00004037 // Use of id.member can only be for a property reference. Do not
4038 // use the 'id' redefinition in this case.
4039 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
John McCall028d3972010-12-15 16:46:44 +00004040 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4041 ObjCImpDecl, HasTemplateArgs);
4042
4043 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
4044 << MemberName << BaseType);
4045 }
4046
4047 // 'Class', unqualified only.
4048 if (OT->isObjCClass()) {
4049 // Only works in a method declaration (??!).
4050 ObjCMethodDecl *MD = getCurMethodDecl();
4051 if (!MD) {
4052 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4053 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4054 ObjCImpDecl, HasTemplateArgs);
4055
4056 goto fail;
4057 }
4058
4059 // Also must look for a getter name which uses property syntax.
4060 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004061 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4062 ObjCMethodDecl *Getter;
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004063 if ((Getter = IFace->lookupClassMethod(Sel))) {
4064 // Check the use of this method.
4065 if (DiagnoseUseOfDecl(Getter, MemberLoc))
4066 return ExprError();
John McCall028d3972010-12-15 16:46:44 +00004067 } else
Fariborz Jahanian74b27562010-12-03 23:37:08 +00004068 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004069 // If we found a getter then this may be a valid dot-reference, we
4070 // will look for the matching setter, in case it is needed.
4071 Selector SetterSel =
John McCall028d3972010-12-15 16:46:44 +00004072 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4073 PP.getSelectorTable(), Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004074 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
4075 if (!Setter) {
4076 // If this reference is in an @implementation, also check for 'private'
4077 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00004078 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004079 }
4080 // Look through local category implementations associated with the class.
4081 if (!Setter)
4082 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004083
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004084 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
4085 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004086
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004087 if (Getter || Setter) {
4088 QualType PType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004089
John McCall09431682010-11-18 19:01:18 +00004090 ExprValueKind VK = VK_LValue;
4091 if (Getter) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004092 PType = Getter->getSendResultType();
John McCall09431682010-11-18 19:01:18 +00004093 if (!getLangOptions().CPlusPlus &&
4094 IsCForbiddenLValueType(Context, PType))
4095 VK = VK_RValue;
4096 } else {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004097 // Get the expression type from Setter's incoming parameter.
4098 PType = (*(Setter->param_end() -1))->getType();
John McCall09431682010-11-18 19:01:18 +00004099 }
4100 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4101
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004102 // FIXME: we must check that the setter has property type.
John McCall12f78a62010-12-02 01:19:52 +00004103 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
4104 PType, VK, OK,
John Wiegley429bb272011-04-08 18:41:53 +00004105 MemberLoc, BaseExpr.take()));
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004106 }
John McCall028d3972010-12-15 16:46:44 +00004107
4108 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4109 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4110 ObjCImpDecl, HasTemplateArgs);
4111
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004112 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall028d3972010-12-15 16:46:44 +00004113 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00004114 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004115
John McCall028d3972010-12-15 16:46:44 +00004116 // Normal property access.
John Wiegley429bb272011-04-08 18:41:53 +00004117 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), MemberName, MemberLoc,
John McCall028d3972010-12-15 16:46:44 +00004118 SourceLocation(), QualType(), false);
Steve Naroff14108da2009-07-10 23:34:53 +00004119 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004120
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004121 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00004122 if (BaseType->isExtVectorType()) {
John McCall5e3c67b2010-12-15 04:42:30 +00004123 // FIXME: this expr should store IsArrow.
Anders Carlsson8f28f992009-08-26 18:25:21 +00004124 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John Wiegley429bb272011-04-08 18:41:53 +00004125 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
John McCall09431682010-11-18 19:01:18 +00004126 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
4127 Member, MemberLoc);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004128 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004129 return ExprError();
John McCall09431682010-11-18 19:01:18 +00004130
John Wiegley429bb272011-04-08 18:41:53 +00004131 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
John McCall09431682010-11-18 19:01:18 +00004132 *Member, MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004133 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004134
John McCall028d3972010-12-15 16:46:44 +00004135 // Adjust builtin-sel to the appropriate redefinition type if that's
4136 // not just a pointer to builtin-sel again.
4137 if (IsArrow &&
4138 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4139 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004140 BaseExpr = ImpCastExprToType(BaseExpr.take(), Context.ObjCSelRedefinitionType,
4141 CK_BitCast);
John McCall028d3972010-12-15 16:46:44 +00004142 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4143 ObjCImpDecl, HasTemplateArgs);
4144 }
4145
4146 // Failure cases.
4147 fail:
4148
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004149 // Recover from dot accesses to pointers, e.g.:
4150 // type *foo;
4151 // foo.bar
4152 // This is actually well-formed in two cases:
4153 // - 'type' is an Objective C type
4154 // - 'bar' is a pseudo-destructor name which happens to refer to
4155 // the appropriate pointer type
John McCall028d3972010-12-15 16:46:44 +00004156 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004157 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4158 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall028d3972010-12-15 16:46:44 +00004159 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley429bb272011-04-08 18:41:53 +00004160 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004161 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall028d3972010-12-15 16:46:44 +00004162
4163 // Recurse as an -> access.
4164 IsArrow = true;
4165 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4166 ObjCImpDecl, HasTemplateArgs);
4167 }
John McCall028d3972010-12-15 16:46:44 +00004168 }
4169
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004170 // If the user is trying to apply -> or . to a function name, it's probably
4171 // because they forgot parentheses to call that function.
4172 bool TryCall = false;
4173 bool Overloaded = false;
4174 UnresolvedSet<8> AllOverloads;
John Wiegley429bb272011-04-08 18:41:53 +00004175 if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(BaseExpr.get())) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004176 AllOverloads.append(Overloads->decls_begin(), Overloads->decls_end());
4177 TryCall = true;
4178 Overloaded = true;
John Wiegley429bb272011-04-08 18:41:53 +00004179 } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(BaseExpr.get())) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004180 if (FunctionDecl* Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
4181 AllOverloads.addDecl(Fun);
4182 TryCall = true;
4183 }
4184 }
John McCall028d3972010-12-15 16:46:44 +00004185
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004186 if (TryCall) {
4187 // Plunder the overload set for something that would make the member
4188 // expression valid.
4189 UnresolvedSet<4> ViableOverloads;
4190 bool HasViableZeroArgOverload = false;
4191 for (OverloadExpr::decls_iterator it = AllOverloads.begin(),
4192 DeclsEnd = AllOverloads.end(); it != DeclsEnd; ++it) {
Matt Beaumont-Gayfbe59942011-03-05 02:42:30 +00004193 // Our overload set may include TemplateDecls, which we'll ignore for the
4194 // purposes of determining whether we can issue a '()' fixit.
4195 if (const FunctionDecl *OverloadDecl = dyn_cast<FunctionDecl>(*it)) {
4196 QualType ResultTy = OverloadDecl->getResultType();
4197 if ((!IsArrow && ResultTy->isRecordType()) ||
4198 (IsArrow && ResultTy->isPointerType() &&
4199 ResultTy->getPointeeType()->isRecordType())) {
4200 ViableOverloads.addDecl(*it);
4201 if (OverloadDecl->getMinRequiredArguments() == 0) {
4202 HasViableZeroArgOverload = true;
4203 }
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004204 }
John McCall028d3972010-12-15 16:46:44 +00004205 }
4206 }
4207
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004208 if (!HasViableZeroArgOverload || ViableOverloads.size() != 1) {
John Wiegley429bb272011-04-08 18:41:53 +00004209 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gayfbe59942011-03-05 02:42:30 +00004210 << (AllOverloads.size() > 1) << 0
John Wiegley429bb272011-04-08 18:41:53 +00004211 << BaseExpr.get()->getSourceRange();
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004212 int ViableOverloadCount = ViableOverloads.size();
4213 int I;
4214 for (I = 0; I < ViableOverloadCount; ++I) {
4215 // FIXME: Magic number for max shown overloads stolen from
4216 // OverloadCandidateSet::NoteCandidates.
4217 if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
4218 break;
4219 }
4220 Diag(ViableOverloads[I].getDecl()->getSourceRange().getBegin(),
4221 diag::note_member_ref_possible_intended_overload);
4222 }
4223 if (I != ViableOverloadCount) {
John Wiegley429bb272011-04-08 18:41:53 +00004224 Diag(BaseExpr.get()->getExprLoc(), diag::note_ovl_too_many_candidates)
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004225 << int(ViableOverloadCount - I);
4226 }
4227 return ExprError();
4228 }
4229 } else {
4230 // We don't have an expression that's convenient to get a Decl from, but we
4231 // can at least check if the type is "function of 0 arguments which returns
4232 // an acceptable type".
4233 const FunctionType *Fun = NULL;
4234 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4235 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4236 TryCall = true;
4237 }
4238 } else if ((Fun = BaseType->getAs<FunctionType>())) {
4239 TryCall = true;
4240 }
John McCall028d3972010-12-15 16:46:44 +00004241
4242 if (TryCall) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004243 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4244 if (FPT->getNumArgs() == 0) {
4245 QualType ResultTy = Fun->getResultType();
4246 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4247 (IsArrow && ResultTy->isPointerType() &&
4248 ResultTy->getPointeeType()->isRecordType());
4249 }
Matt Beaumont-Gay26ae5dd2011-02-17 02:54:17 +00004250 }
John McCall028d3972010-12-15 16:46:44 +00004251 }
4252 }
4253
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004254 if (TryCall) {
4255 // At this point, we know BaseExpr looks like it's potentially callable with
4256 // 0 arguments, and that it returns something of a reasonable type, so we
4257 // can emit a fixit and carry on pretending that BaseExpr was actually a
4258 // CallExpr.
4259 SourceLocation ParenInsertionLoc =
John Wiegley429bb272011-04-08 18:41:53 +00004260 PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
4261 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004262 << int(Overloaded) << 1
John Wiegley429bb272011-04-08 18:41:53 +00004263 << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004264 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
John Wiegley429bb272011-04-08 18:41:53 +00004265 ExprResult NewBase = ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004266 MultiExprArg(*this, 0, 0),
4267 ParenInsertionLoc);
4268 if (NewBase.isInvalid())
4269 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004270 BaseExpr = NewBase;
4271 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004272 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4273 ObjCImpDecl, HasTemplateArgs);
4274 }
4275
Douglas Gregor214f31a2009-03-27 06:00:30 +00004276 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
John Wiegley429bb272011-04-08 18:41:53 +00004277 << BaseType << BaseExpr.get()->getSourceRange();
Douglas Gregor214f31a2009-03-27 06:00:30 +00004278
Douglas Gregor214f31a2009-03-27 06:00:30 +00004279 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00004280}
4281
John McCall129e2df2009-11-30 22:42:35 +00004282/// The main callback when the parser finds something like
4283/// expression . [nested-name-specifier] identifier
4284/// expression -> [nested-name-specifier] identifier
4285/// where 'identifier' encompasses a fairly broad spectrum of
4286/// possibilities, including destructor and operator references.
4287///
4288/// \param OpKind either tok::arrow or tok::period
4289/// \param HasTrailingLParen whether the next token is '(', which
4290/// is used to diagnose mis-uses of special members that can
4291/// only be called
4292/// \param ObjCImpDecl the current ObjC @implementation decl;
4293/// this is an ugly hack around the fact that ObjC @implementations
4294/// aren't properly put in the context chain
John McCall60d7b3a2010-08-24 06:29:42 +00004295ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall5e3c67b2010-12-15 04:42:30 +00004296 SourceLocation OpLoc,
4297 tok::TokenKind OpKind,
4298 CXXScopeSpec &SS,
4299 UnqualifiedId &Id,
4300 Decl *ObjCImpDecl,
4301 bool HasTrailingLParen) {
John McCall129e2df2009-11-30 22:42:35 +00004302 if (SS.isSet() && SS.isInvalid())
4303 return ExprError();
4304
Francois Pichetdbee3412011-01-18 05:04:39 +00004305 // Warn about the explicit constructor calls Microsoft extension.
4306 if (getLangOptions().Microsoft &&
4307 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4308 Diag(Id.getSourceRange().getBegin(),
4309 diag::ext_ms_explicit_constructor_call);
4310
John McCall129e2df2009-11-30 22:42:35 +00004311 TemplateArgumentListInfo TemplateArgsBuffer;
4312
4313 // Decompose the name into its component parts.
Abramo Bagnara25777432010-08-11 22:01:17 +00004314 DeclarationNameInfo NameInfo;
John McCall129e2df2009-11-30 22:42:35 +00004315 const TemplateArgumentListInfo *TemplateArgs;
4316 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00004317 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004318
Abramo Bagnara25777432010-08-11 22:01:17 +00004319 DeclarationName Name = NameInfo.getName();
John McCall129e2df2009-11-30 22:42:35 +00004320 bool IsArrow = (OpKind == tok::arrow);
4321
4322 NamedDecl *FirstQualifierInScope
4323 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4324 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4325
4326 // This is a postfix expression, so get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004327 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004328 if (Result.isInvalid()) return ExprError();
4329 Base = Result.take();
John McCall129e2df2009-11-30 22:42:35 +00004330
Douglas Gregor01e56ae2010-04-12 20:54:26 +00004331 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4332 isDependentScopeSpecifier(SS)) {
John McCall9ae2f072010-08-23 23:25:46 +00004333 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00004334 IsArrow, OpLoc,
4335 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00004336 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004337 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00004338 LookupResult R(*this, NameInfo, LookupMemberName);
John Wiegley429bb272011-04-08 18:41:53 +00004339 ExprResult BaseResult = Owned(Base);
4340 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCallad00b772010-06-16 08:42:20 +00004341 SS, ObjCImpDecl, TemplateArgs != 0);
John Wiegley429bb272011-04-08 18:41:53 +00004342 if (BaseResult.isInvalid())
4343 return ExprError();
4344 Base = BaseResult.take();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004345
John McCallad00b772010-06-16 08:42:20 +00004346 if (Result.isInvalid()) {
4347 Owned(Base);
4348 return ExprError();
4349 }
John McCall129e2df2009-11-30 22:42:35 +00004350
John McCallad00b772010-06-16 08:42:20 +00004351 if (Result.get()) {
4352 // The only way a reference to a destructor can be used is to
4353 // immediately call it, which falls into this case. If the
4354 // next token is not a '(', produce a diagnostic and build the
4355 // call now.
4356 if (!HasTrailingLParen &&
4357 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCall9ae2f072010-08-23 23:25:46 +00004358 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall129e2df2009-11-30 22:42:35 +00004359
John McCallad00b772010-06-16 08:42:20 +00004360 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00004361 }
4362
John McCall9ae2f072010-08-23 23:25:46 +00004363 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00004364 OpLoc, IsArrow, SS, FirstQualifierInScope,
4365 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004366 }
4367
4368 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00004369}
4370
John McCall60d7b3a2010-08-24 06:29:42 +00004371ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00004372 FunctionDecl *FD,
4373 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00004374 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004375 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00004376 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00004377 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00004378 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00004379 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004380 return ExprError();
4381 }
4382
4383 if (Param->hasUninstantiatedDefaultArg()) {
4384 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00004385
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004386 // Instantiate the expression.
4387 MultiLevelTemplateArgumentList ArgList
4388 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00004389
Nico Weber08e41a62010-11-29 18:19:25 +00004390 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004391 = ArgList.getInnermost();
4392 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4393 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004394
Nico Weber08e41a62010-11-29 18:19:25 +00004395 ExprResult Result;
4396 {
4397 // C++ [dcl.fct.default]p5:
4398 // The names in the [default argument] expression are bound, and
4399 // the semantic constraints are checked, at the point where the
4400 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00004401 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00004402 Result = SubstExpr(UninstExpr, ArgList);
4403 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004404 if (Result.isInvalid())
4405 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004406
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004407 // Check the expression as an initializer for the parameter.
4408 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004409 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004410 InitializationKind Kind
4411 = InitializationKind::CreateCopy(Param->getLocation(),
4412 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4413 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00004414
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004415 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4416 Result = InitSeq.Perform(*this, Entity, Kind,
4417 MultiExprArg(*this, &ResultE, 1));
4418 if (Result.isInvalid())
4419 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004420
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004421 // Build the default argument expression.
4422 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4423 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004424 }
4425
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004426 // If the default expression creates temporaries, we need to
4427 // push them to the current stack of expression temporaries so they'll
4428 // be properly destroyed.
4429 // FIXME: We should really be rebuilding the default argument with new
4430 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00004431 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4432 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4433 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4434 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4435 ExprTemporaries.push_back(Temporary);
4436 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004437
4438 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00004439 // Just mark all of the declarations in this potentially-evaluated expression
4440 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004441 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00004442 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004443}
4444
Douglas Gregor88a35142008-12-22 05:46:06 +00004445/// ConvertArgumentsForCall - Converts the arguments specified in
4446/// Args/NumArgs to the parameter types of the function FDecl with
4447/// function prototype Proto. Call is the call expression itself, and
4448/// Fn is the function expression. For a C++ member function, this
4449/// routine does not attempt to convert the object argument. Returns
4450/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004451bool
4452Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00004453 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00004454 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00004455 Expr **Args, unsigned NumArgs,
4456 SourceLocation RParenLoc) {
John McCall8e10f3b2011-02-26 05:39:39 +00004457 // Bail out early if calling a builtin with custom typechecking.
4458 // We don't need to do this in the
4459 if (FDecl)
4460 if (unsigned ID = FDecl->getBuiltinID())
4461 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4462 return false;
4463
Mike Stumpeed9cac2009-02-19 03:04:26 +00004464 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00004465 // assignment, to the types of the corresponding parameter, ...
4466 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004467 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004468
Douglas Gregor88a35142008-12-22 05:46:06 +00004469 // If too few arguments are available (and we don't have default
4470 // arguments for the remaining parameters), don't make the call.
4471 if (NumArgs < NumArgsInProto) {
4472 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4473 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004474 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00004475 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00004476 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00004477 }
4478
4479 // If too many are passed and not variadic, error on the extras and drop
4480 // them.
4481 if (NumArgs > NumArgsInProto) {
4482 if (!Proto->isVariadic()) {
4483 Diag(Args[NumArgsInProto]->getLocStart(),
4484 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004485 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00004486 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00004487 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4488 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00004489
4490 // Emit the location of the prototype.
4491 if (FDecl && !FDecl->getBuiltinID())
4492 Diag(FDecl->getLocStart(),
4493 diag::note_typecheck_call_too_many_args)
4494 << FDecl;
4495
Douglas Gregor88a35142008-12-22 05:46:06 +00004496 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004497 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004498 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004499 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004500 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004501 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004502 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004503 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4504 if (Fn->getType()->isBlockPointerType())
4505 CallType = VariadicBlock; // Block
4506 else if (isa<MemberExpr>(Fn))
4507 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004508 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004509 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004510 if (Invalid)
4511 return true;
4512 unsigned TotalNumArgs = AllArgs.size();
4513 for (unsigned i = 0; i < TotalNumArgs; ++i)
4514 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004515
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004516 return false;
4517}
Mike Stumpeed9cac2009-02-19 03:04:26 +00004518
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004519bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4520 FunctionDecl *FDecl,
4521 const FunctionProtoType *Proto,
4522 unsigned FirstProtoArg,
4523 Expr **Args, unsigned NumArgs,
4524 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004525 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004526 unsigned NumArgsInProto = Proto->getNumArgs();
4527 unsigned NumArgsToCheck = NumArgs;
4528 bool Invalid = false;
4529 if (NumArgs != NumArgsInProto)
4530 // Use default arguments for missing arguments
4531 NumArgsToCheck = NumArgsInProto;
4532 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00004533 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004534 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004535 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004536
Douglas Gregor88a35142008-12-22 05:46:06 +00004537 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004538 if (ArgIx < NumArgs) {
4539 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004540
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004541 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4542 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004543 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004544 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004545 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004546
Douglas Gregora188ff22009-12-22 16:09:06 +00004547 // Pass the argument
4548 ParmVarDecl *Param = 0;
4549 if (FDecl && i < FDecl->getNumParams())
4550 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00004551
Douglas Gregora188ff22009-12-22 16:09:06 +00004552 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004553 Param? InitializedEntity::InitializeParameter(Context, Param)
4554 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCall60d7b3a2010-08-24 06:29:42 +00004555 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00004556 SourceLocation(),
4557 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00004558 if (ArgE.isInvalid())
4559 return true;
4560
4561 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004562 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00004563 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004564
John McCall60d7b3a2010-08-24 06:29:42 +00004565 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004566 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004567 if (ArgExpr.isInvalid())
4568 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004569
Anders Carlsson56c5e332009-08-25 03:49:14 +00004570 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004571 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004572 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004573 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004574
Douglas Gregor88a35142008-12-22 05:46:06 +00004575 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004576 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00004577
4578 // Assume that extern "C" functions with variadic arguments that
4579 // return __unknown_anytype aren't *really* variadic.
4580 if (Proto->getResultType() == Context.UnknownAnyTy &&
4581 FDecl && FDecl->isExternC()) {
4582 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4583 ExprResult arg;
4584 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
4585 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
4586 else
4587 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4588 Invalid |= arg.isInvalid();
4589 AllArgs.push_back(arg.take());
4590 }
4591
4592 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4593 } else {
4594 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4595 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4596 Invalid |= Arg.isInvalid();
4597 AllArgs.push_back(Arg.take());
4598 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004599 }
4600 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004601 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00004602}
4603
John McCall755d8492011-04-12 00:42:48 +00004604/// Given a function expression of unknown-any type, try to rebuild it
4605/// to have a function type.
4606static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4607
Steve Narofff69936d2007-09-16 03:34:24 +00004608/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00004609/// This provides the location of the left/right parens and a list of comma
4610/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00004611ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004612Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004613 MultiExprArg args, SourceLocation RParenLoc,
4614 Expr *ExecConfig) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00004615 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00004616
4617 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004618 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00004619 if (Result.isInvalid()) return ExprError();
4620 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00004621
John McCall9ae2f072010-08-23 23:25:46 +00004622 Expr **Args = args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004623
Douglas Gregor88a35142008-12-22 05:46:06 +00004624 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00004625 // If this is a pseudo-destructor expression, build the call immediately.
4626 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4627 if (NumArgs > 0) {
4628 // Pseudo-destructor calls should not have any arguments.
4629 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00004630 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00004631 SourceRange(Args[0]->getLocStart(),
4632 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00004633
Douglas Gregora71d8192009-09-04 17:36:40 +00004634 NumArgs = 0;
4635 }
Mike Stump1eb44332009-09-09 15:08:12 +00004636
Douglas Gregora71d8192009-09-04 17:36:40 +00004637 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00004638 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00004639 }
Mike Stump1eb44332009-09-09 15:08:12 +00004640
Douglas Gregor17330012009-02-04 15:01:18 +00004641 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00004642 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00004643 // FIXME: Will need to cache the results of name lookup (including ADL) in
4644 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00004645 bool Dependent = false;
4646 if (Fn->isTypeDependent())
4647 Dependent = true;
4648 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4649 Dependent = true;
4650
Peter Collingbournee08ce652011-02-09 21:07:24 +00004651 if (Dependent) {
4652 if (ExecConfig) {
4653 return Owned(new (Context) CUDAKernelCallExpr(
4654 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4655 Context.DependentTy, VK_RValue, RParenLoc));
4656 } else {
4657 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4658 Context.DependentTy, VK_RValue,
4659 RParenLoc));
4660 }
4661 }
Douglas Gregor17330012009-02-04 15:01:18 +00004662
4663 // Determine whether this is a call to an object (C++ [over.call.object]).
4664 if (Fn->getType()->isRecordType())
4665 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004666 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00004667
John McCall755d8492011-04-12 00:42:48 +00004668 if (Fn->getType() == Context.UnknownAnyTy) {
4669 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4670 if (result.isInvalid()) return ExprError();
4671 Fn = result.take();
4672 }
4673
John McCall129e2df2009-11-30 22:42:35 +00004674 Expr *NakedFn = Fn->IgnoreParens();
4675
4676 // Determine whether this is a call to an unresolved member function.
4677 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4678 // If lookup was unresolved but not dependent (i.e. didn't find
4679 // an unresolved using declaration), it has to be an overloaded
4680 // function set, which means it must contain either multiple
4681 // declarations (all methods or method templates) or a single
4682 // method template.
4683 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor2b147f02010-04-25 21:15:30 +00004684 isa<FunctionTemplateDecl>(
4685 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00004686 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00004687
John McCallaa81e162009-12-01 22:10:20 +00004688 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004689 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00004690 }
4691
Douglas Gregorfa047642009-02-04 00:32:51 +00004692 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00004693 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00004694 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00004695 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00004696 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004697 RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00004698 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004699
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004700 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00004701 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCall2de56d12010-08-25 11:45:40 +00004702 if (BO->getOpcode() == BO_PtrMemD ||
4703 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00004704 if (const FunctionProtoType *FPT
4705 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004706 QualType ResultTy = FPT->getCallResultType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00004707 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004708
Douglas Gregorfdc13a02011-02-04 12:57:49 +00004709 // Check that the object type isn't more qualified than the
4710 // member function we're calling.
4711 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4712 Qualifiers ObjectQuals
4713 = BO->getOpcode() == BO_PtrMemD
4714 ? BO->getLHS()->getType().getQualifiers()
4715 : BO->getLHS()->getType()->getAs<PointerType>()
4716 ->getPointeeType().getQualifiers();
4717
4718 Qualifiers Difference = ObjectQuals - FuncQuals;
4719 Difference.removeObjCGCAttr();
4720 Difference.removeAddressSpace();
4721 if (Difference) {
4722 std::string QualsString = Difference.getAsString();
4723 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4724 << BO->getType().getUnqualifiedType()
4725 << QualsString
4726 << (QualsString.find(' ') == std::string::npos? 1 : 2);
4727 }
4728
John McCall9ae2f072010-08-23 23:25:46 +00004729 CXXMemberCallExpr *TheCall
Abramo Bagnara6c572f12010-12-03 21:39:42 +00004730 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCallf89e55a2010-11-18 06:31:45 +00004731 NumArgs, ResultTy, VK,
John McCall9ae2f072010-08-23 23:25:46 +00004732 RParenLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004733
4734 if (CheckCallReturnType(FPT->getResultType(),
4735 BO->getRHS()->getSourceRange().getBegin(),
John McCall9ae2f072010-08-23 23:25:46 +00004736 TheCall, 0))
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004737 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00004738
John McCall9ae2f072010-08-23 23:25:46 +00004739 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004740 RParenLoc))
4741 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004742
John McCall9ae2f072010-08-23 23:25:46 +00004743 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004744 }
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004745 }
4746 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004747 }
4748
Douglas Gregorfa047642009-02-04 00:32:51 +00004749 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00004750 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004751 // lookup and whether there were any explicitly-specified template arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004752
Eli Friedmanefa42f72009-12-26 03:35:45 +00004753 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00004754 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4755 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4756 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004757 RParenLoc, ExecConfig);
Douglas Gregoref9b1492010-11-09 20:03:54 +00004758 }
4759
John McCall3b4294e2009-12-16 12:17:52 +00004760 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00004761 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4762 if (UnOp->getOpcode() == UO_AddrOf)
4763 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4764
John McCall3b4294e2009-12-16 12:17:52 +00004765 if (isa<DeclRefExpr>(NakedFn))
4766 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4767
Peter Collingbournee08ce652011-02-09 21:07:24 +00004768 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4769 ExecConfig);
4770}
4771
4772ExprResult
4773Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4774 MultiExprArg execConfig, SourceLocation GGGLoc) {
4775 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4776 if (!ConfigDecl)
4777 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4778 << "cudaConfigureCall");
4779 QualType ConfigQTy = ConfigDecl->getType();
4780
4781 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4782 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4783
4784 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCallaa81e162009-12-01 22:10:20 +00004785}
4786
John McCall3b4294e2009-12-16 12:17:52 +00004787/// BuildResolvedCallExpr - Build a call to a resolved expression,
4788/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00004789/// unary-convert to an expression of function-pointer or
4790/// block-pointer type.
4791///
4792/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00004793ExprResult
John McCallaa81e162009-12-01 22:10:20 +00004794Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4795 SourceLocation LParenLoc,
4796 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004797 SourceLocation RParenLoc,
4798 Expr *Config) {
John McCallaa81e162009-12-01 22:10:20 +00004799 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4800
Chris Lattner04421082008-04-08 04:40:51 +00004801 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00004802 ExprResult Result = UsualUnaryConversions(Fn);
4803 if (Result.isInvalid())
4804 return ExprError();
4805 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00004806
Chris Lattner925e60d2007-12-28 05:29:59 +00004807 // Make the call expr early, before semantic checks. This guarantees cleanup
4808 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00004809 CallExpr *TheCall;
4810 if (Config) {
4811 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4812 cast<CallExpr>(Config),
4813 Args, NumArgs,
4814 Context.BoolTy,
4815 VK_RValue,
4816 RParenLoc);
4817 } else {
4818 TheCall = new (Context) CallExpr(Context, Fn,
4819 Args, NumArgs,
4820 Context.BoolTy,
4821 VK_RValue,
4822 RParenLoc);
4823 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004824
John McCall8e10f3b2011-02-26 05:39:39 +00004825 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4826
4827 // Bail out early if calling a builtin with custom typechecking.
4828 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4829 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4830
John McCall1de4d4e2011-04-07 08:22:57 +00004831 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00004832 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00004833 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00004834 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4835 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00004836 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00004837 if (FuncT == 0)
4838 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4839 << Fn->getType() << Fn->getSourceRange());
4840 } else if (const BlockPointerType *BPT =
4841 Fn->getType()->getAs<BlockPointerType>()) {
4842 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4843 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00004844 // Handle calls to expressions of unknown-any type.
4845 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00004846 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004847 if (rewrite.isInvalid()) return ExprError();
4848 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00004849 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004850 goto retry;
4851 }
4852
Sebastian Redl0eb23302009-01-19 00:08:26 +00004853 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4854 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00004855 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004856
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004857 if (getLangOptions().CUDA) {
4858 if (Config) {
4859 // CUDA: Kernel calls must be to global functions
4860 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4861 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4862 << FDecl->getName() << Fn->getSourceRange());
4863
4864 // CUDA: Kernel function must have 'void' return type
4865 if (!FuncT->getResultType()->isVoidType())
4866 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4867 << Fn->getType() << Fn->getSourceRange());
4868 }
4869 }
4870
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004871 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004872 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00004873 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004874 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004875 return ExprError();
4876
Chris Lattner925e60d2007-12-28 05:29:59 +00004877 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004878 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00004879 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004880
Douglas Gregor72564e72009-02-26 23:50:07 +00004881 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00004882 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00004883 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004884 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004885 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004886 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004887
Douglas Gregor74734d52009-04-02 15:37:10 +00004888 if (FDecl) {
4889 // Check if we have too few/too many template arguments, based
4890 // on our knowledge of the function definition.
4891 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004892 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004893 const FunctionProtoType *Proto
4894 = Def->getType()->getAs<FunctionProtoType>();
4895 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004896 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4897 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004898 }
Douglas Gregor46542412010-10-25 20:39:23 +00004899
4900 // If the function we're calling isn't a function prototype, but we have
4901 // a function prototype from a prior declaratiom, use that prototype.
4902 if (!FDecl->hasPrototype())
4903 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004904 }
4905
Steve Naroffb291ab62007-08-28 23:30:39 +00004906 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004907 for (unsigned i = 0; i != NumArgs; i++) {
4908 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004909
4910 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004911 InitializedEntity Entity
4912 = InitializedEntity::InitializeParameter(Context,
4913 Proto->getArgType(i));
4914 ExprResult ArgE = PerformCopyInitialization(Entity,
4915 SourceLocation(),
4916 Owned(Arg));
4917 if (ArgE.isInvalid())
4918 return true;
4919
4920 Arg = ArgE.takeAs<Expr>();
4921
4922 } else {
John Wiegley429bb272011-04-08 18:41:53 +00004923 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4924
4925 if (ArgE.isInvalid())
4926 return true;
4927
4928 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00004929 }
4930
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004931 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4932 Arg->getType(),
4933 PDiag(diag::err_call_incomplete_argument)
4934 << Arg->getSourceRange()))
4935 return ExprError();
4936
Chris Lattner925e60d2007-12-28 05:29:59 +00004937 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004938 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004939 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004940
Douglas Gregor88a35142008-12-22 05:46:06 +00004941 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4942 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004943 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4944 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004945
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004946 // Check for sentinels
4947 if (NDecl)
4948 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004949
Chris Lattner59907c42007-08-10 20:18:51 +00004950 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004951 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00004952 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00004953 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004954
John McCall8e10f3b2011-02-26 05:39:39 +00004955 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004956 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004957 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00004958 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00004959 return ExprError();
4960 }
Chris Lattner59907c42007-08-10 20:18:51 +00004961
John McCall9ae2f072010-08-23 23:25:46 +00004962 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004963}
4964
John McCall60d7b3a2010-08-24 06:29:42 +00004965ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004966Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004967 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004968 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004969 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004970 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004971
4972 TypeSourceInfo *TInfo;
4973 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4974 if (!TInfo)
4975 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4976
John McCall9ae2f072010-08-23 23:25:46 +00004977 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004978}
4979
John McCall60d7b3a2010-08-24 06:29:42 +00004980ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004981Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00004982 SourceLocation RParenLoc, Expr *literalExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004983 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004984
Eli Friedman6223c222008-05-20 05:22:08 +00004985 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004986 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4987 PDiag(diag::err_illegal_decl_array_incomplete_type)
4988 << SourceRange(LParenLoc,
4989 literalExpr->getSourceRange().getEnd())))
4990 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004991 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004992 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4993 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004994 } else if (!literalType->isDependentType() &&
4995 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004996 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00004997 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00004998 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004999 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00005000
Douglas Gregor99a2e602009-12-16 01:38:02 +00005001 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00005002 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005003 InitializationKind Kind
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005004 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor99a2e602009-12-16 01:38:02 +00005005 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00005006 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00005007 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00005008 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00005009 &literalType);
5010 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005011 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00005012 literalExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00005013
Chris Lattner371f2582008-12-04 23:50:19 +00005014 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00005015 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00005016 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005017 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00005018 }
Eli Friedman08544622009-12-22 02:35:53 +00005019
John McCallf89e55a2010-11-18 06:31:45 +00005020 // In C, compound literals are l-values for some reason.
5021 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
5022
John McCall1d7d8d62010-01-19 22:33:45 +00005023 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCallf89e55a2010-11-18 06:31:45 +00005024 VK, literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00005025}
5026
John McCall60d7b3a2010-08-24 06:29:42 +00005027ExprResult
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005028Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005029 SourceLocation RBraceLoc) {
5030 unsigned NumInit = initlist.size();
John McCall9ae2f072010-08-23 23:25:46 +00005031 Expr **InitList = initlist.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00005032
Steve Naroff08d92e42007-09-15 18:49:24 +00005033 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00005034 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005035
Ted Kremenek709210f2010-04-13 23:39:13 +00005036 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
5037 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00005038 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005039 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00005040}
5041
John McCallf3ea8cf2010-11-14 08:17:51 +00005042/// Prepares for a scalar cast, performing all the necessary stages
5043/// except the final cast and returning the kind required.
John Wiegley429bb272011-04-08 18:41:53 +00005044static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00005045 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5046 // Also, callers should have filtered out the invalid cases with
5047 // pointers. Everything else should be possible.
5048
John Wiegley429bb272011-04-08 18:41:53 +00005049 QualType SrcTy = Src.get()->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00005050 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00005051 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00005052
John McCalldaa8e4e2010-11-15 09:13:47 +00005053 switch (SrcTy->getScalarTypeKind()) {
5054 case Type::STK_MemberPointer:
5055 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005056
John McCalldaa8e4e2010-11-15 09:13:47 +00005057 case Type::STK_Pointer:
5058 switch (DestTy->getScalarTypeKind()) {
5059 case Type::STK_Pointer:
5060 return DestTy->isObjCObjectPointerType() ?
John McCallf3ea8cf2010-11-14 08:17:51 +00005061 CK_AnyPointerToObjCPointerCast :
5062 CK_BitCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005063 case Type::STK_Bool:
5064 return CK_PointerToBoolean;
5065 case Type::STK_Integral:
5066 return CK_PointerToIntegral;
5067 case Type::STK_Floating:
5068 case Type::STK_FloatingComplex:
5069 case Type::STK_IntegralComplex:
5070 case Type::STK_MemberPointer:
5071 llvm_unreachable("illegal cast from pointer");
5072 }
5073 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005074
John McCalldaa8e4e2010-11-15 09:13:47 +00005075 case Type::STK_Bool: // casting from bool is like casting from an integer
5076 case Type::STK_Integral:
5077 switch (DestTy->getScalarTypeKind()) {
5078 case Type::STK_Pointer:
John Wiegley429bb272011-04-08 18:41:53 +00005079 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00005080 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00005081 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005082 case Type::STK_Bool:
5083 return CK_IntegralToBoolean;
5084 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00005085 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005086 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00005087 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00005088 case Type::STK_IntegralComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005089 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5090 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00005091 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005092 case Type::STK_FloatingComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005093 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5094 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00005095 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005096 case Type::STK_MemberPointer:
5097 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005098 }
5099 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005100
John McCalldaa8e4e2010-11-15 09:13:47 +00005101 case Type::STK_Floating:
5102 switch (DestTy->getScalarTypeKind()) {
5103 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00005104 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005105 case Type::STK_Bool:
5106 return CK_FloatingToBoolean;
5107 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00005108 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00005109 case Type::STK_FloatingComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005110 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5111 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00005112 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005113 case Type::STK_IntegralComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005114 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5115 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00005116 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005117 case Type::STK_Pointer:
5118 llvm_unreachable("valid float->pointer cast?");
5119 case Type::STK_MemberPointer:
5120 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005121 }
5122 break;
5123
John McCalldaa8e4e2010-11-15 09:13:47 +00005124 case Type::STK_FloatingComplex:
5125 switch (DestTy->getScalarTypeKind()) {
5126 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005127 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005128 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005129 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00005130 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005131 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005132 if (S.Context.hasSameType(ET, DestTy))
5133 return CK_FloatingComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00005134 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00005135 return CK_FloatingCast;
5136 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005137 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00005138 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00005139 case Type::STK_Integral:
John Wiegley429bb272011-04-08 18:41:53 +00005140 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5141 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00005142 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00005143 case Type::STK_Pointer:
5144 llvm_unreachable("valid complex float->pointer cast?");
5145 case Type::STK_MemberPointer:
5146 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005147 }
5148 break;
5149
John McCalldaa8e4e2010-11-15 09:13:47 +00005150 case Type::STK_IntegralComplex:
5151 switch (DestTy->getScalarTypeKind()) {
5152 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005153 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005154 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005155 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00005156 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005157 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005158 if (S.Context.hasSameType(ET, DestTy))
5159 return CK_IntegralComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00005160 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00005161 return CK_IntegralCast;
5162 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005163 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00005164 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00005165 case Type::STK_Floating:
John Wiegley429bb272011-04-08 18:41:53 +00005166 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5167 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00005168 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00005169 case Type::STK_Pointer:
5170 llvm_unreachable("valid complex int->pointer cast?");
5171 case Type::STK_MemberPointer:
5172 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005173 }
5174 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00005175 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005176
John McCallf3ea8cf2010-11-14 08:17:51 +00005177 llvm_unreachable("Unhandled scalar cast");
5178 return CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00005179}
5180
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005181/// CheckCastTypes - Check type constraints for casting between types.
John Wiegley429bb272011-04-08 18:41:53 +00005182ExprResult Sema::CheckCastTypes(SourceRange TyR, QualType castType,
5183 Expr *castExpr, CastKind& Kind, ExprValueKind &VK,
5184 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall1de4d4e2011-04-07 08:22:57 +00005185 if (castExpr->getType() == Context.UnknownAnyTy)
5186 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
5187
Sebastian Redl9cc11e72009-07-25 15:41:38 +00005188 if (getLangOptions().CPlusPlus)
Douglas Gregor40749ee2010-11-03 00:35:38 +00005189 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
5190 castExpr->getLocEnd()),
John McCallf89e55a2010-11-18 06:31:45 +00005191 castType, VK, castExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005192 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00005193
John McCallfb8721c2011-04-10 19:13:55 +00005194 assert(!castExpr->getType()->isPlaceholderType());
5195
John McCallf89e55a2010-11-18 06:31:45 +00005196 // We only support r-value casts in C.
5197 VK = VK_RValue;
5198
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005199 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5200 // type needs to be scalar.
5201 if (castType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00005202 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley429bb272011-04-08 18:41:53 +00005203 ExprResult castExprRes = IgnoredValueConversions(castExpr);
5204 if (castExprRes.isInvalid())
5205 return ExprError();
5206 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00005207
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005208 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00005209 Kind = CK_ToVoid;
John Wiegley429bb272011-04-08 18:41:53 +00005210 return Owned(castExpr);
Anders Carlssonebeaf202009-10-16 02:35:04 +00005211 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005212
John Wiegley429bb272011-04-08 18:41:53 +00005213 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
5214 if (castExprRes.isInvalid())
5215 return ExprError();
5216 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00005217
Eli Friedman8d438082010-07-17 20:43:49 +00005218 if (RequireCompleteType(TyR.getBegin(), castType,
5219 diag::err_typecheck_cast_to_incomplete))
John Wiegley429bb272011-04-08 18:41:53 +00005220 return ExprError();
Eli Friedman8d438082010-07-17 20:43:49 +00005221
Anders Carlssonebeaf202009-10-16 02:35:04 +00005222 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00005223 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005224 (castType->isStructureType() || castType->isUnionType())) {
5225 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005226 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005227 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5228 << castType << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005229 Kind = CK_NoOp;
John Wiegley429bb272011-04-08 18:41:53 +00005230 return Owned(castExpr);
Anders Carlssonc3516322009-10-16 02:48:28 +00005231 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005232
Anders Carlssonc3516322009-10-16 02:48:28 +00005233 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005234 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00005235 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005236 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005237 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005238 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005239 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00005240 castExpr->getType()) &&
5241 !Field->isUnnamedBitfield()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005242 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5243 << castExpr->getSourceRange();
5244 break;
5245 }
5246 }
John Wiegley429bb272011-04-08 18:41:53 +00005247 if (Field == FieldEnd) {
5248 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005249 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005250 return ExprError();
5251 }
John McCall2de56d12010-08-25 11:45:40 +00005252 Kind = CK_ToUnion;
John Wiegley429bb272011-04-08 18:41:53 +00005253 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005254 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005255
Anders Carlssonc3516322009-10-16 02:48:28 +00005256 // Reject any other conversions to non-scalar types.
John Wiegley429bb272011-04-08 18:41:53 +00005257 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlssonc3516322009-10-16 02:48:28 +00005258 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005259 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00005260 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005261
John McCallf3ea8cf2010-11-14 08:17:51 +00005262 // The type we're casting to is known to be a scalar or vector.
5263
5264 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005265 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00005266 !castExpr->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005267 Diag(castExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005268 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00005269 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005270 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00005271 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005272
5273 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00005274 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005275
Anton Yartsevd06fea82011-03-27 09:32:40 +00005276 if (castType->isVectorType()) {
5277 if (castType->getAs<VectorType>()->getVectorKind() ==
5278 VectorType::AltiVecVector &&
5279 (castExpr->getType()->isIntegerType() ||
5280 castExpr->getType()->isFloatingType())) {
5281 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00005282 return Owned(castExpr);
5283 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
5284 return ExprError();
Anton Yartsevd06fea82011-03-27 09:32:40 +00005285 } else
John Wiegley429bb272011-04-08 18:41:53 +00005286 return Owned(castExpr);
Anton Yartsevd06fea82011-03-27 09:32:40 +00005287 }
John Wiegley429bb272011-04-08 18:41:53 +00005288 if (castExpr->getType()->isVectorType()) {
5289 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
5290 return ExprError();
5291 else
5292 return Owned(castExpr);
5293 }
Anders Carlssonc3516322009-10-16 02:48:28 +00005294
John McCallf3ea8cf2010-11-14 08:17:51 +00005295 // The source and target types are both scalars, i.e.
5296 // - arithmetic types (fundamental, enum, and complex)
5297 // - all kinds of pointers
5298 // Note that member pointers were filtered out with C++, above.
5299
John Wiegley429bb272011-04-08 18:41:53 +00005300 if (isa<ObjCSelectorExpr>(castExpr)) {
5301 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
5302 return ExprError();
5303 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005304
John McCallf3ea8cf2010-11-14 08:17:51 +00005305 // If either type is a pointer, the other type has to be either an
5306 // integer or a pointer.
Anders Carlssonc3516322009-10-16 02:48:28 +00005307 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00005308 QualType castExprType = castExpr->getType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005309 if (!castExprType->isIntegralType(Context) &&
John Wiegley429bb272011-04-08 18:41:53 +00005310 castExprType->isArithmeticType()) {
5311 Diag(castExpr->getLocStart(),
5312 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00005313 << castExprType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005314 return ExprError();
5315 }
Eli Friedman41826bb2009-05-01 02:23:58 +00005316 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005317 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
5318 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00005319 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005320 return ExprError();
5321 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005322 }
Anders Carlsson82debc72009-10-18 18:12:03 +00005323
John Wiegley429bb272011-04-08 18:41:53 +00005324 castExprRes = Owned(castExpr);
5325 Kind = PrepareScalarCast(*this, castExprRes, castType);
5326 if (castExprRes.isInvalid())
5327 return ExprError();
5328 castExpr = castExprRes.take();
John McCallb7f4ffe2010-08-12 21:44:57 +00005329
John McCallf3ea8cf2010-11-14 08:17:51 +00005330 if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00005331 CheckCastAlign(castExpr, castType, TyR);
5332
John Wiegley429bb272011-04-08 18:41:53 +00005333 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005334}
5335
Anders Carlssonc3516322009-10-16 02:48:28 +00005336bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00005337 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00005338 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005339
Anders Carlssona64db8f2007-11-27 05:51:55 +00005340 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00005341 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00005342 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00005343 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00005344 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005345 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00005346 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005347 } else
5348 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005349 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00005350 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005351
John McCall2de56d12010-08-25 11:45:40 +00005352 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005353 return false;
5354}
5355
John Wiegley429bb272011-04-08 18:41:53 +00005356ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5357 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00005358 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005359
Anders Carlsson16a89042009-10-16 05:23:41 +00005360 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005361
Nate Begeman9b10da62009-06-27 22:05:55 +00005362 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5363 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00005364 if (SrcTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005365 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
5366 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00005367 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00005368 return ExprError();
5369 }
John McCall2de56d12010-08-25 11:45:40 +00005370 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00005371 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00005372 }
5373
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005374 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00005375 // conversion will take place first from scalar to elt type, and then
5376 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005377 if (SrcTy->isPointerType())
5378 return Diag(R.getBegin(),
5379 diag::err_invalid_conversion_between_vector_and_scalar)
5380 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00005381
5382 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00005383 ExprResult CastExprRes = Owned(CastExpr);
5384 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
5385 if (CastExprRes.isInvalid())
5386 return ExprError();
5387 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005388
John McCall2de56d12010-08-25 11:45:40 +00005389 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00005390 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00005391}
5392
John McCall60d7b3a2010-08-24 06:29:42 +00005393ExprResult
John McCallb3d87482010-08-24 05:47:05 +00005394Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005395 SourceLocation RParenLoc, Expr *castExpr) {
5396 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005397 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00005398
John McCall9d125032010-01-15 18:39:57 +00005399 TypeSourceInfo *castTInfo;
5400 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5401 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00005402 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00005403
Nate Begeman2ef13e52009-08-10 23:49:36 +00005404 // If the Expr being casted is a ParenListExpr, handle it specially.
5405 if (isa<ParenListExpr>(castExpr))
John McCall9ae2f072010-08-23 23:25:46 +00005406 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCall42f56b52010-01-18 19:35:47 +00005407 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00005408
John McCall9ae2f072010-08-23 23:25:46 +00005409 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallb042fdf2010-01-15 18:56:44 +00005410}
5411
John McCall60d7b3a2010-08-24 06:29:42 +00005412ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00005413Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005414 SourceLocation RParenLoc, Expr *castExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005415 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00005416 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00005417 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +00005418 ExprResult CastResult =
5419 CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
5420 Kind, VK, BasePath);
5421 if (CastResult.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005422 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00005423 castExpr = CastResult.take();
Anders Carlsson0aebc812009-09-09 21:33:21 +00005424
John McCallf871d0c2010-08-07 06:22:56 +00005425 return Owned(CStyleCastExpr::Create(Context,
John Wiegley429bb272011-04-08 18:41:53 +00005426 Ty->getType().getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +00005427 VK, Kind, castExpr, &BasePath, Ty,
John McCallf871d0c2010-08-07 06:22:56 +00005428 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005429}
5430
Nate Begeman2ef13e52009-08-10 23:49:36 +00005431/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5432/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005433ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005434Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005435 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5436 if (!E)
5437 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00005438
John McCall60d7b3a2010-08-24 06:29:42 +00005439 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00005440
Nate Begeman2ef13e52009-08-10 23:49:36 +00005441 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00005442 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5443 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00005444
John McCall9ae2f072010-08-23 23:25:46 +00005445 if (Result.isInvalid()) return ExprError();
5446
5447 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005448}
5449
John McCall60d7b3a2010-08-24 06:29:42 +00005450ExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00005451Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00005452 SourceLocation RParenLoc, Expr *Op,
John McCall42f56b52010-01-18 19:35:47 +00005453 TypeSourceInfo *TInfo) {
John McCall9ae2f072010-08-23 23:25:46 +00005454 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCall42f56b52010-01-18 19:35:47 +00005455 QualType Ty = TInfo->getType();
Anton Yartsevd06fea82011-03-27 09:32:40 +00005456 bool isVectorLiteral = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005457
Anton Yartsevd06fea82011-03-27 09:32:40 +00005458 // Check for an altivec or OpenCL literal,
John Thompson8bb59a82010-06-30 22:55:51 +00005459 // i.e. all the elements are integer constants.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005460 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5461 if (PE->getNumExprs() == 0) {
5462 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5463 return ExprError();
5464 }
John Thompson8bb59a82010-06-30 22:55:51 +00005465 if (PE->getNumExprs() == 1) {
5466 if (!PE->getExpr(0)->getType()->isVectorType())
Anton Yartsevd06fea82011-03-27 09:32:40 +00005467 isVectorLiteral = true;
John Thompson8bb59a82010-06-30 22:55:51 +00005468 }
5469 else
Anton Yartsevd06fea82011-03-27 09:32:40 +00005470 isVectorLiteral = true;
John Thompson8bb59a82010-06-30 22:55:51 +00005471 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00005472
Anton Yartsevd06fea82011-03-27 09:32:40 +00005473 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
John Thompson8bb59a82010-06-30 22:55:51 +00005474 // then handle it as such.
Anton Yartsevd06fea82011-03-27 09:32:40 +00005475 if (isVectorLiteral) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005476 llvm::SmallVector<Expr *, 8> initExprs;
Anton Yartsevd06fea82011-03-27 09:32:40 +00005477 // '(...)' form of vector initialization in AltiVec: the number of
5478 // initializers must be one or must match the size of the vector.
5479 // If a single value is specified in the initializer then it will be
5480 // replicated to all the components of the vector
5481 if (Ty->getAs<VectorType>()->getVectorKind() ==
5482 VectorType::AltiVecVector) {
5483 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5484 // The number of initializers must be one or must match the size of the
5485 // vector. If a single value is specified in the initializer then it will
5486 // be replicated to all the components of the vector
5487 if (PE->getNumExprs() == 1) {
5488 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00005489 ExprResult Literal = Owned(PE->getExpr(0));
5490 Literal = ImpCastExprToType(Literal.take(), ElemTy,
5491 PrepareScalarCast(*this, Literal, ElemTy));
5492 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
Anton Yartsevd06fea82011-03-27 09:32:40 +00005493 }
5494 else if (PE->getNumExprs() < numElems) {
5495 Diag(PE->getExprLoc(),
5496 diag::err_incorrect_number_of_vector_initializers);
5497 return ExprError();
5498 }
5499 else
5500 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5501 initExprs.push_back(PE->getExpr(i));
5502 }
5503 else
5504 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5505 initExprs.push_back(PE->getExpr(i));
Nate Begeman2ef13e52009-08-10 23:49:36 +00005506
5507 // FIXME: This means that pretty-printing the final AST will produce curly
5508 // braces instead of the original commas.
Ted Kremenek709210f2010-04-13 23:39:13 +00005509 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5510 &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00005511 initExprs.size(), RParenLoc);
5512 E->setType(Ty);
John McCall9ae2f072010-08-23 23:25:46 +00005513 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005514 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005515 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00005516 // sequence of BinOp comma operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005517 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCall9ae2f072010-08-23 23:25:46 +00005518 if (Result.isInvalid()) return ExprError();
5519 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005520 }
5521}
5522
John McCall60d7b3a2010-08-24 06:29:42 +00005523ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00005524 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005525 MultiExprArg Val,
John McCallb3d87482010-08-24 05:47:05 +00005526 ParsedType TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005527 unsigned nexprs = Val.size();
5528 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005529 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5530 Expr *expr;
5531 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5532 expr = new (Context) ParenExpr(L, R, exprs[0]);
5533 else
5534 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005535 return Owned(expr);
5536}
5537
Chandler Carruth82214a82011-02-18 23:54:50 +00005538/// \brief Emit a specialized diagnostic when one expression is a null pointer
5539/// constant and the other is not a pointer.
5540bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5541 SourceLocation QuestionLoc) {
5542 Expr *NullExpr = LHS;
5543 Expr *NonPointerExpr = RHS;
5544 Expr::NullPointerConstantKind NullKind =
5545 NullExpr->isNullPointerConstant(Context,
5546 Expr::NPC_ValueDependentIsNotNull);
5547
5548 if (NullKind == Expr::NPCK_NotNull) {
5549 NullExpr = RHS;
5550 NonPointerExpr = LHS;
5551 NullKind =
5552 NullExpr->isNullPointerConstant(Context,
5553 Expr::NPC_ValueDependentIsNotNull);
5554 }
5555
5556 if (NullKind == Expr::NPCK_NotNull)
5557 return false;
5558
5559 if (NullKind == Expr::NPCK_ZeroInteger) {
5560 // In this case, check to make sure that we got here from a "NULL"
5561 // string in the source code.
5562 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00005563 SourceLocation loc = NullExpr->getExprLoc();
5564 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00005565 return false;
5566 }
5567
5568 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5569 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5570 << NonPointerExpr->getType() << DiagType
5571 << NonPointerExpr->getSourceRange();
5572 return true;
5573}
5574
Sebastian Redl28507842009-02-26 14:39:58 +00005575/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5576/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00005577/// C99 6.5.15
John Wiegley429bb272011-04-08 18:41:53 +00005578QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005579 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00005580 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00005581
John McCallfb8721c2011-04-10 19:13:55 +00005582 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00005583 if (!lhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00005584 LHS = move(lhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005585
John McCallfb8721c2011-04-10 19:13:55 +00005586 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00005587 if (!rhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00005588 RHS = move(rhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005589
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005590 // C++ is sufficiently different to merit its own checker.
5591 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00005592 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00005593
5594 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005595 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005596
John Wiegley429bb272011-04-08 18:41:53 +00005597 Cond = UsualUnaryConversions(Cond.take());
5598 if (Cond.isInvalid())
5599 return QualType();
5600 LHS = UsualUnaryConversions(LHS.take());
5601 if (LHS.isInvalid())
5602 return QualType();
5603 RHS = UsualUnaryConversions(RHS.take());
5604 if (RHS.isInvalid())
5605 return QualType();
5606
5607 QualType CondTy = Cond.get()->getType();
5608 QualType LHSTy = LHS.get()->getType();
5609 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005610
Reid Spencer5f016e22007-07-11 17:01:13 +00005611 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005612 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begeman6155d732010-09-20 22:41:17 +00005613 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5614 // Throw an error if its not either.
5615 if (getLangOptions().OpenCL) {
5616 if (!CondTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005617 Diag(Cond.get()->getLocStart(),
Nate Begeman6155d732010-09-20 22:41:17 +00005618 diag::err_typecheck_cond_expect_scalar_or_vector)
5619 << CondTy;
5620 return QualType();
5621 }
5622 }
5623 else {
John Wiegley429bb272011-04-08 18:41:53 +00005624 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00005625 << CondTy;
5626 return QualType();
5627 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005628 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005629
Chris Lattner70d67a92008-01-06 22:42:25 +00005630 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005631 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5632 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00005633
Nate Begeman6155d732010-09-20 22:41:17 +00005634 // OpenCL: If the condition is a vector, and both operands are scalar,
5635 // attempt to implicity convert them to the vector type to act like the
5636 // built in select.
5637 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5638 // Both operands should be of scalar type.
5639 if (!LHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005640 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00005641 << CondTy;
5642 return QualType();
5643 }
5644 if (!RHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005645 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00005646 << CondTy;
5647 return QualType();
5648 }
5649 // Implicity convert these scalars to the type of the condition.
John Wiegley429bb272011-04-08 18:41:53 +00005650 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5651 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begeman6155d732010-09-20 22:41:17 +00005652 }
5653
Chris Lattner70d67a92008-01-06 22:42:25 +00005654 // If both operands have arithmetic type, do the usual arithmetic conversions
5655 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005656 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5657 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00005658 if (LHS.isInvalid() || RHS.isInvalid())
5659 return QualType();
5660 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00005661 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005662
Chris Lattner70d67a92008-01-06 22:42:25 +00005663 // If both operands are the same structure or union type, the result is that
5664 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005665 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5666 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00005667 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005668 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005669 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005670 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005671 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005672 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005673
Chris Lattner70d67a92008-01-06 22:42:25 +00005674 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005675 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005676 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5677 if (!LHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00005678 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5679 << RHS.get()->getSourceRange();
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005680 if (!RHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00005681 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5682 << LHS.get()->getSourceRange();
5683 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
5684 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00005685 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00005686 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00005687 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5688 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005689 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley429bb272011-04-08 18:41:53 +00005690 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005691 // promote the null to a pointer.
John Wiegley429bb272011-04-08 18:41:53 +00005692 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005693 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005694 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005695 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley429bb272011-04-08 18:41:53 +00005696 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5697 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005698 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005699 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005700
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005701 // All objective-c pointer type analysis is done here.
5702 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5703 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005704 if (LHS.isInvalid() || RHS.isInvalid())
5705 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005706 if (!compositeType.isNull())
5707 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005708
5709
Steve Naroff7154a772009-07-01 14:36:47 +00005710 // Handle block pointer types.
5711 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5712 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5713 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5714 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00005715 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5716 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005717 return destType;
5718 }
5719 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00005720 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00005721 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005722 }
Steve Naroff7154a772009-07-01 14:36:47 +00005723 // We have 2 block pointer types.
5724 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5725 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005726 return LHSTy;
5727 }
Steve Naroff7154a772009-07-01 14:36:47 +00005728 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00005729 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5730 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005731
Steve Naroff7154a772009-07-01 14:36:47 +00005732 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5733 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00005734 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00005735 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005736 // In this situation, we assume void* type. No especially good
5737 // reason, but this is what gcc does, and we do have to pick
5738 // to get a consistent AST.
5739 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00005740 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5741 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00005742 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005743 }
Steve Naroff7154a772009-07-01 14:36:47 +00005744 // The block pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00005745 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5746 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00005747 return LHSTy;
5748 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005749
Steve Naroff7154a772009-07-01 14:36:47 +00005750 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5751 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5752 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00005753 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5754 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00005755
5756 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5757 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5758 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00005759 QualType destPointee
5760 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005761 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005762 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005763 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005764 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005765 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005766 return destType;
5767 }
5768 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00005769 QualType destPointee
5770 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005771 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005772 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005773 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005774 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005775 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005776 return destType;
5777 }
5778
5779 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5780 // Two identical pointer types are always compatible.
5781 return LHSTy;
5782 }
5783 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5784 rhptee.getUnqualifiedType())) {
5785 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00005786 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00005787 // In this situation, we assume void* type. No especially good
5788 // reason, but this is what gcc does, and we do have to pick
5789 // to get a consistent AST.
5790 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00005791 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5792 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005793 return incompatTy;
5794 }
5795 // The pointer types are compatible.
5796 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5797 // differently qualified versions of compatible types, the result type is
5798 // a pointer to an appropriately qualified version of the *composite*
5799 // type.
5800 // FIXME: Need to calculate the composite type.
5801 // FIXME: Need to add qualifiers
John Wiegley429bb272011-04-08 18:41:53 +00005802 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5803 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005804 return LHSTy;
5805 }
Mike Stump1eb44332009-09-09 15:08:12 +00005806
John McCall404cd162010-11-13 01:35:44 +00005807 // GCC compatibility: soften pointer/integer mismatch. Note that
5808 // null pointers have been filtered out by this point.
Steve Naroff7154a772009-07-01 14:36:47 +00005809 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5810 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley429bb272011-04-08 18:41:53 +00005811 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5812 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005813 return RHSTy;
5814 }
5815 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5816 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley429bb272011-04-08 18:41:53 +00005817 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5818 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005819 return LHSTy;
5820 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00005821
Chandler Carruth82214a82011-02-18 23:54:50 +00005822 // Emit a better diagnostic if one of the expressions is a null pointer
5823 // constant and the other is not a pointer type. In this case, the user most
5824 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00005825 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00005826 return QualType();
5827
Chris Lattner70d67a92008-01-06 22:42:25 +00005828 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005829 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00005830 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005831 return QualType();
5832}
5833
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005834/// FindCompositeObjCPointerType - Helper method to find composite type of
5835/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00005836QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005837 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00005838 QualType LHSTy = LHS.get()->getType();
5839 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005840
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005841 // Handle things like Class and struct objc_class*. Here we case the result
5842 // to the pseudo-builtin, because that will be implicitly cast back to the
5843 // redefinition type if an attempt is made to access its fields.
5844 if (LHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005845 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00005846 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005847 return LHSTy;
5848 }
5849 if (RHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005850 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00005851 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005852 return RHSTy;
5853 }
5854 // And the same for struct objc_object* / id
5855 if (LHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005856 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00005857 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005858 return LHSTy;
5859 }
5860 if (RHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005861 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00005862 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005863 return RHSTy;
5864 }
5865 // And the same for struct objc_selector* / SEL
5866 if (Context.isObjCSelType(LHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00005867 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00005868 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005869 return LHSTy;
5870 }
5871 if (Context.isObjCSelType(RHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00005872 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00005873 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005874 return RHSTy;
5875 }
5876 // Check constraints for Objective-C object pointers types.
5877 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005878
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005879 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5880 // Two identical object pointer types are always compatible.
5881 return LHSTy;
5882 }
5883 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5884 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5885 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005886
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005887 // If both operands are interfaces and either operand can be
5888 // assigned to the other, use that type as the composite
5889 // type. This allows
5890 // xxx ? (A*) a : (B*) b
5891 // where B is a subclass of A.
5892 //
5893 // Additionally, as for assignment, if either type is 'id'
5894 // allow silent coercion. Finally, if the types are
5895 // incompatible then make sure to use 'id' as the composite
5896 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005897
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005898 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5899 // It could return the composite type.
5900 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5901 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5902 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5903 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5904 } else if ((LHSTy->isObjCQualifiedIdType() ||
5905 RHSTy->isObjCQualifiedIdType()) &&
5906 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5907 // Need to handle "id<xx>" explicitly.
5908 // GCC allows qualified id and any Objective-C type to devolve to
5909 // id. Currently localizing to here until clear this should be
5910 // part of ObjCQualifiedIdTypesAreCompatible.
5911 compositeType = Context.getObjCIdType();
5912 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5913 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005914 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005915 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5916 ;
5917 else {
5918 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5919 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00005920 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005921 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00005922 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5923 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005924 return incompatTy;
5925 }
5926 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00005927 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5928 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005929 return compositeType;
5930 }
5931 // Check Objective-C object pointer types and 'void *'
5932 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5933 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5934 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5935 QualType destPointee
5936 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5937 QualType destType = Context.getPointerType(destPointee);
5938 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005939 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005940 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005941 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005942 return destType;
5943 }
5944 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5945 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5946 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5947 QualType destPointee
5948 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5949 QualType destType = Context.getPointerType(destPointee);
5950 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005951 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005952 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005953 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005954 return destType;
5955 }
5956 return QualType();
5957}
5958
Steve Narofff69936d2007-09-16 03:34:24 +00005959/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005960/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005961ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005962 SourceLocation ColonLoc,
5963 Expr *CondExpr, Expr *LHSExpr,
5964 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005965 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5966 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005967 OpaqueValueExpr *opaqueValue = 0;
5968 Expr *commonExpr = 0;
5969 if (LHSExpr == 0) {
5970 commonExpr = CondExpr;
5971
5972 // We usually want to apply unary conversions *before* saving, except
5973 // in the special case of a C++ l-value conditional.
5974 if (!(getLangOptions().CPlusPlus
5975 && !commonExpr->isTypeDependent()
5976 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5977 && commonExpr->isGLValue()
5978 && commonExpr->isOrdinaryOrBitFieldObject()
5979 && RHSExpr->isOrdinaryOrBitFieldObject()
5980 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005981 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5982 if (commonRes.isInvalid())
5983 return ExprError();
5984 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005985 }
5986
5987 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5988 commonExpr->getType(),
5989 commonExpr->getValueKind(),
5990 commonExpr->getObjectKind());
5991 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005992 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005993
John McCallf89e55a2010-11-18 06:31:45 +00005994 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005995 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005996 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5997 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005998 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005999 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6000 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006001 return ExprError();
6002
John McCall56ca35d2011-02-17 10:25:35 +00006003 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00006004 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
6005 LHS.take(), ColonLoc,
6006 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00006007
6008 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00006009 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
6010 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00006011}
6012
John McCalle4be87e2011-01-31 23:13:11 +00006013// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00006014// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00006015// routine is it effectively iqnores the qualifiers on the top level pointee.
6016// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6017// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00006018static Sema::AssignConvertType
6019checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6020 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6021 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006022
Reid Spencer5f016e22007-07-11 17:01:13 +00006023 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00006024 const Type *lhptee, *rhptee;
6025 Qualifiers lhq, rhq;
6026 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
6027 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006028
John McCalle4be87e2011-01-31 23:13:11 +00006029 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006030
6031 // C99 6.5.16.1p1: This following citation is common to constraints
6032 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6033 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00006034 Qualifiers lq;
6035
6036 if (!lhq.compatiblyIncludes(rhq)) {
6037 // Treat address-space mismatches as fatal. TODO: address subspaces
6038 if (lhq.getAddressSpace() != rhq.getAddressSpace())
6039 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6040
John McCall22348732011-03-26 02:56:45 +00006041 // It's okay to add or remove GC qualifiers when converting to
6042 // and from void*.
6043 else if (lhq.withoutObjCGCAttr().compatiblyIncludes(rhq.withoutObjCGCAttr())
6044 && (lhptee->isVoidType() || rhptee->isVoidType()))
6045 ; // keep old
6046
John McCall86c05f32011-02-01 00:10:29 +00006047 // For GCC compatibility, other qualifier mismatches are treated
6048 // as still compatible in C.
6049 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6050 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006051
Mike Stumpeed9cac2009-02-19 03:04:26 +00006052 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6053 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00006054 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006055 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00006056 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00006057 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006058
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006059 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00006060 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00006061 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006062 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006063
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006064 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00006065 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00006066 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006067
6068 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00006069 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00006070 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006071 }
John McCall86c05f32011-02-01 00:10:29 +00006072
Mike Stumpeed9cac2009-02-19 03:04:26 +00006073 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00006074 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00006075 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6076 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006077 // Check if the pointee types are compatible ignoring the sign.
6078 // We explicitly check for char so that we catch "char" vs
6079 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00006080 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00006081 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00006082 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00006083 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006084
Chris Lattner6a2b9262009-10-17 20:33:28 +00006085 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00006086 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00006087 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00006088 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00006089
John McCall86c05f32011-02-01 00:10:29 +00006090 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006091 // Types are compatible ignoring the sign. Qualifier incompatibility
6092 // takes priority over sign incompatibility because the sign
6093 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00006094 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006095 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00006096
John McCalle4be87e2011-01-31 23:13:11 +00006097 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006098 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006099
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006100 // If we are a multi-level pointer, it's possible that our issue is simply
6101 // one of qualification - e.g. char ** -> const char ** is not allowed. If
6102 // the eventual target type is the same and the pointers have the same
6103 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00006104 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006105 do {
John McCall86c05f32011-02-01 00:10:29 +00006106 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6107 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00006108 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006109
John McCall86c05f32011-02-01 00:10:29 +00006110 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00006111 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006112 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006113
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006114 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00006115 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006116 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00006117 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006118}
6119
John McCalle4be87e2011-01-31 23:13:11 +00006120/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00006121/// block pointer types are compatible or whether a block and normal pointer
6122/// are compatible. It is more restrict than comparing two function pointer
6123// types.
John McCalle4be87e2011-01-31 23:13:11 +00006124static Sema::AssignConvertType
6125checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
6126 QualType rhsType) {
6127 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6128 assert(rhsType.isCanonical() && "RHS not canonicalized!");
6129
Steve Naroff1c7d0672008-09-04 15:10:53 +00006130 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006131
Steve Naroff1c7d0672008-09-04 15:10:53 +00006132 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCalle4be87e2011-01-31 23:13:11 +00006133 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
6134 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006135
John McCalle4be87e2011-01-31 23:13:11 +00006136 // In C++, the types have to match exactly.
6137 if (S.getLangOptions().CPlusPlus)
6138 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006139
John McCalle4be87e2011-01-31 23:13:11 +00006140 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006141
Steve Naroff1c7d0672008-09-04 15:10:53 +00006142 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00006143 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6144 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006145
John McCalle4be87e2011-01-31 23:13:11 +00006146 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
6147 return Sema::IncompatibleBlockPointer;
6148
Steve Naroff1c7d0672008-09-04 15:10:53 +00006149 return ConvTy;
6150}
6151
John McCalle4be87e2011-01-31 23:13:11 +00006152/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006153/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00006154static Sema::AssignConvertType
6155checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6156 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
6157 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
6158
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006159 if (lhsType->isObjCBuiltinType()) {
6160 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00006161 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
6162 !rhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00006163 return Sema::IncompatiblePointer;
6164 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006165 }
6166 if (rhsType->isObjCBuiltinType()) {
6167 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00006168 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
6169 !lhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00006170 return Sema::IncompatiblePointer;
6171 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006172 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006173 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006174 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006175 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006176 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006177
John McCalle4be87e2011-01-31 23:13:11 +00006178 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
6179 return Sema::CompatiblePointerDiscardsQualifiers;
6180
6181 if (S.Context.typesAreCompatible(lhsType, rhsType))
6182 return Sema::Compatible;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006183 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00006184 return Sema::IncompatibleObjCQualifiedId;
6185 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006186}
6187
John McCall1c23e912010-11-16 02:32:08 +00006188Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00006189Sema::CheckAssignmentConstraints(SourceLocation Loc,
6190 QualType lhsType, QualType rhsType) {
John McCall1c23e912010-11-16 02:32:08 +00006191 // Fake up an opaque expression. We don't actually care about what
6192 // cast operations are required, so if CheckAssignmentConstraints
6193 // adds casts to this they'll be wasted, but fortunately that doesn't
6194 // usually happen on valid code.
Douglas Gregorb608b982011-01-28 02:26:04 +00006195 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00006196 ExprResult rhsPtr = &rhs;
John McCall1c23e912010-11-16 02:32:08 +00006197 CastKind K = CK_Invalid;
6198
6199 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
6200}
6201
Mike Stumpeed9cac2009-02-19 03:04:26 +00006202/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6203/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00006204/// pointers. Here are some objectionable examples that GCC considers warnings:
6205///
6206/// int a, *pint;
6207/// short *pshort;
6208/// struct foo *pfoo;
6209///
6210/// pint = pshort; // warning: assignment from incompatible pointer type
6211/// a = pint; // warning: assignment makes integer from pointer without a cast
6212/// pint = a; // warning: assignment makes pointer from integer without a cast
6213/// pint = pfoo; // warning: assignment from incompatible pointer type
6214///
6215/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00006216/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00006217///
John McCalldaa8e4e2010-11-15 09:13:47 +00006218/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00006219Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00006220Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCalldaa8e4e2010-11-15 09:13:47 +00006221 CastKind &Kind) {
John Wiegley429bb272011-04-08 18:41:53 +00006222 QualType rhsType = rhs.get()->getType();
John McCall1c23e912010-11-16 02:32:08 +00006223
Chris Lattnerfc144e22008-01-04 23:18:45 +00006224 // Get canonical types. We're not formatting these types, just comparing
6225 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00006226 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
6227 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006228
John McCallb6cfa242011-01-31 22:28:28 +00006229 // Common case: no conversion required.
John McCalldaa8e4e2010-11-15 09:13:47 +00006230 if (lhsType == rhsType) {
6231 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00006232 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00006233 }
6234
Douglas Gregor9d293df2008-10-28 00:22:11 +00006235 // If the left-hand side is a reference type, then we are in a
6236 // (rare!) case where we've allowed the use of references in C,
6237 // e.g., as a parameter type in a built-in function. In this case,
6238 // just make sure that the type referenced is compatible with the
6239 // right-hand side type. The caller is responsible for adjusting
6240 // lhsType so that the resulting expression does not have reference
6241 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00006242 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006243 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
6244 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00006245 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006246 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00006247 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00006248 }
John McCallb6cfa242011-01-31 22:28:28 +00006249
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006250 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6251 // to the same ExtVector type.
6252 if (lhsType->isExtVectorType()) {
6253 if (rhsType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00006254 return Incompatible;
6255 if (rhsType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00006256 // CK_VectorSplat does T -> vector T, so first cast to the
6257 // element type.
6258 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
6259 if (elType != rhsType) {
6260 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley429bb272011-04-08 18:41:53 +00006261 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00006262 }
6263 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006264 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006265 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006266 }
Mike Stump1eb44332009-09-09 15:08:12 +00006267
John McCallb6cfa242011-01-31 22:28:28 +00006268 // Conversions to or from vector type.
Nate Begemanbe2341d2008-07-14 18:02:46 +00006269 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00006270 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00006271 // Allow assignments of an AltiVec vector type to an equivalent GCC
6272 // vector type and vice versa
6273 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6274 Kind = CK_BitCast;
6275 return Compatible;
6276 }
6277
Douglas Gregor255210e2010-08-06 10:14:59 +00006278 // If we are allowing lax vector conversions, and LHS and RHS are both
6279 // vectors, the total size only needs to be the same. This is a bitcast;
6280 // no bits are changed but the result type is different.
6281 if (getLangOptions().LaxVectorConversions &&
John McCalldaa8e4e2010-11-15 09:13:47 +00006282 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00006283 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006284 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00006285 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00006286 }
6287 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006288 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006289
John McCallb6cfa242011-01-31 22:28:28 +00006290 // Arithmetic conversions.
Douglas Gregor88623ad2010-05-23 21:53:47 +00006291 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00006292 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall1c23e912010-11-16 02:32:08 +00006293 Kind = PrepareScalarCast(*this, rhs, lhsType);
Reid Spencer5f016e22007-07-11 17:01:13 +00006294 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006295 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006296
John McCallb6cfa242011-01-31 22:28:28 +00006297 // Conversions to normal pointers.
6298 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6299 // U* -> T*
John McCalldaa8e4e2010-11-15 09:13:47 +00006300 if (isa<PointerType>(rhsType)) {
6301 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00006302 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006303 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006304
John McCallb6cfa242011-01-31 22:28:28 +00006305 // int -> T*
6306 if (rhsType->isIntegerType()) {
6307 Kind = CK_IntegralToPointer; // FIXME: null?
6308 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006309 }
John McCallb6cfa242011-01-31 22:28:28 +00006310
6311 // C pointers are not compatible with ObjC object pointers,
6312 // with two exceptions:
6313 if (isa<ObjCObjectPointerType>(rhsType)) {
6314 // - conversions to void*
6315 if (lhsPointer->getPointeeType()->isVoidType()) {
6316 Kind = CK_AnyPointerToObjCPointerCast;
6317 return Compatible;
6318 }
6319
6320 // - conversions from 'Class' to the redefinition type
6321 if (rhsType->isObjCClassType() &&
6322 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006323 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006324 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006325 }
Steve Naroffb4406862008-09-29 18:10:17 +00006326
John McCallb6cfa242011-01-31 22:28:28 +00006327 Kind = CK_BitCast;
6328 return IncompatiblePointer;
6329 }
6330
6331 // U^ -> void*
6332 if (rhsType->getAs<BlockPointerType>()) {
6333 if (lhsPointer->getPointeeType()->isVoidType()) {
6334 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006335 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006336 }
Steve Naroffb4406862008-09-29 18:10:17 +00006337 }
John McCallb6cfa242011-01-31 22:28:28 +00006338
Steve Naroff1c7d0672008-09-04 15:10:53 +00006339 return Incompatible;
6340 }
6341
John McCallb6cfa242011-01-31 22:28:28 +00006342 // Conversions to block pointers.
Steve Naroff1c7d0672008-09-04 15:10:53 +00006343 if (isa<BlockPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006344 // U^ -> T^
6345 if (rhsType->isBlockPointerType()) {
6346 Kind = CK_AnyPointerToBlockPointerCast;
John McCalle4be87e2011-01-31 23:13:11 +00006347 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00006348 }
6349
6350 // int or null -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00006351 if (rhsType->isIntegerType()) {
6352 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00006353 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006354 }
6355
John McCallb6cfa242011-01-31 22:28:28 +00006356 // id -> T^
6357 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6358 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006359 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006360 }
Steve Naroffb4406862008-09-29 18:10:17 +00006361
John McCallb6cfa242011-01-31 22:28:28 +00006362 // void* -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00006363 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00006364 if (RHSPT->getPointeeType()->isVoidType()) {
6365 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006366 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006367 }
John McCalldaa8e4e2010-11-15 09:13:47 +00006368
Chris Lattnerfc144e22008-01-04 23:18:45 +00006369 return Incompatible;
6370 }
6371
John McCallb6cfa242011-01-31 22:28:28 +00006372 // Conversions to Objective-C pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00006373 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006374 // A* -> B*
6375 if (rhsType->isObjCObjectPointerType()) {
6376 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00006377 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00006378 }
6379
6380 // int or null -> A*
John McCalldaa8e4e2010-11-15 09:13:47 +00006381 if (rhsType->isIntegerType()) {
6382 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00006383 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006384 }
6385
John McCallb6cfa242011-01-31 22:28:28 +00006386 // In general, C pointers are not compatible with ObjC object pointers,
6387 // with two exceptions:
Steve Naroff14108da2009-07-10 23:34:53 +00006388 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006389 // - conversions from 'void*'
6390 if (rhsType->isVoidPointerType()) {
6391 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006392 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006393 }
6394
6395 // - conversions to 'Class' from its redefinition type
6396 if (lhsType->isObjCClassType() &&
6397 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6398 Kind = CK_BitCast;
6399 return Compatible;
6400 }
6401
6402 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006403 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006404 }
John McCallb6cfa242011-01-31 22:28:28 +00006405
6406 // T^ -> A*
6407 if (rhsType->isBlockPointerType()) {
6408 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00006409 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006410 }
6411
Steve Naroff14108da2009-07-10 23:34:53 +00006412 return Incompatible;
6413 }
John McCallb6cfa242011-01-31 22:28:28 +00006414
6415 // Conversions from pointers that are not covered by the above.
Chris Lattner78eca282008-04-07 06:49:41 +00006416 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006417 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006418 if (lhsType == Context.BoolTy) {
6419 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006420 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006421 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006422
John McCallb6cfa242011-01-31 22:28:28 +00006423 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006424 if (lhsType->isIntegerType()) {
6425 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006426 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006427 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006428
Chris Lattnerfc144e22008-01-04 23:18:45 +00006429 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00006430 }
John McCallb6cfa242011-01-31 22:28:28 +00006431
6432 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff14108da2009-07-10 23:34:53 +00006433 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006434 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006435 if (lhsType == Context.BoolTy) {
6436 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00006437 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006438 }
Steve Naroff14108da2009-07-10 23:34:53 +00006439
John McCallb6cfa242011-01-31 22:28:28 +00006440 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006441 if (lhsType->isIntegerType()) {
6442 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00006443 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006444 }
6445
Steve Naroff14108da2009-07-10 23:34:53 +00006446 return Incompatible;
6447 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006448
John McCallb6cfa242011-01-31 22:28:28 +00006449 // struct A -> struct B
Chris Lattnerfc144e22008-01-04 23:18:45 +00006450 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006451 if (Context.typesAreCompatible(lhsType, rhsType)) {
6452 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00006453 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006454 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006455 }
John McCallb6cfa242011-01-31 22:28:28 +00006456
Reid Spencer5f016e22007-07-11 17:01:13 +00006457 return Incompatible;
6458}
6459
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006460/// \brief Constructs a transparent union from an expression that is
6461/// used to initialize the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00006462static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006463 QualType UnionType, FieldDecl *Field) {
6464 // Build an initializer list that designates the appropriate member
6465 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00006466 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00006467 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00006468 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006469 SourceLocation());
6470 Initializer->setType(UnionType);
6471 Initializer->setInitializedFieldInUnion(Field);
6472
6473 // Build a compound literal constructing a value of the transparent
6474 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00006475 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00006476 EResult = S.Owned(
6477 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6478 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006479}
6480
6481Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00006482Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
6483 QualType FromType = rExpr.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006484
Mike Stump1eb44332009-09-09 15:08:12 +00006485 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006486 // transparent_union GCC extension.
6487 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006488 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006489 return Incompatible;
6490
6491 // The field to initialize within the transparent union.
6492 RecordDecl *UD = UT->getDecl();
6493 FieldDecl *InitField = 0;
6494 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006495 for (RecordDecl::field_iterator it = UD->field_begin(),
6496 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006497 it != itend; ++it) {
6498 if (it->getType()->isPointerType()) {
6499 // If the transparent union contains a pointer type, we allow:
6500 // 1) void pointer
6501 // 2) null pointer constant
6502 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00006503 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006504 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006505 InitField = *it;
6506 break;
6507 }
Mike Stump1eb44332009-09-09 15:08:12 +00006508
John Wiegley429bb272011-04-08 18:41:53 +00006509 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006510 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006511 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006512 InitField = *it;
6513 break;
6514 }
6515 }
6516
John McCalldaa8e4e2010-11-15 09:13:47 +00006517 CastKind Kind = CK_Invalid;
John Wiegley429bb272011-04-08 18:41:53 +00006518 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006519 == Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +00006520 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006521 InitField = *it;
6522 break;
6523 }
6524 }
6525
6526 if (!InitField)
6527 return Incompatible;
6528
John Wiegley429bb272011-04-08 18:41:53 +00006529 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006530 return Compatible;
6531}
6532
Chris Lattner5cf216b2008-01-04 18:04:52 +00006533Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00006534Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00006535 if (getLangOptions().CPlusPlus) {
6536 if (!lhsType->isRecordType()) {
6537 // C++ 5.17p3: If the left operand is not of class type, the
6538 // expression is implicitly converted (C++ 4) to the
6539 // cv-unqualified type of the left operand.
John Wiegley429bb272011-04-08 18:41:53 +00006540 ExprResult Res = PerformImplicitConversion(rExpr.get(),
6541 lhsType.getUnqualifiedType(),
6542 AA_Assigning);
6543 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00006544 return Incompatible;
John Wiegley429bb272011-04-08 18:41:53 +00006545 rExpr = move(Res);
Chris Lattner2c4463f2009-04-12 09:02:39 +00006546 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00006547 }
6548
6549 // FIXME: Currently, we fall through and treat C++ classes like C
6550 // structures.
John McCallf6a16482010-12-04 03:47:34 +00006551 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00006552
Steve Naroff529a4ad2007-11-27 17:58:44 +00006553 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6554 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00006555 if ((lhsType->isPointerType() ||
6556 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00006557 lhsType->isBlockPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00006558 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006559 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006560 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00006561 return Compatible;
6562 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006563
Chris Lattner943140e2007-10-16 02:55:40 +00006564 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00006565 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00006566 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00006567 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00006568 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00006569 // Suppress this for references: C++ 8.5.3p5.
John Wiegley429bb272011-04-08 18:41:53 +00006570 if (!lhsType->isReferenceType()) {
6571 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
6572 if (rExpr.isInvalid())
6573 return Incompatible;
6574 }
Steve Narofff1120de2007-08-24 22:33:52 +00006575
John McCalldaa8e4e2010-11-15 09:13:47 +00006576 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006577 Sema::AssignConvertType result =
John McCall1c23e912010-11-16 02:32:08 +00006578 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006579
Steve Narofff1120de2007-08-24 22:33:52 +00006580 // C99 6.5.16.1p2: The value of the right operand is converted to the
6581 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00006582 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6583 // so that we can use references in built-in functions even in C.
6584 // The getNonReferenceType() call makes sure that the resulting expression
6585 // does not have reference type.
John Wiegley429bb272011-04-08 18:41:53 +00006586 if (result != Incompatible && rExpr.get()->getType() != lhsType)
6587 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00006588 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00006589}
6590
John Wiegley429bb272011-04-08 18:41:53 +00006591QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006592 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley429bb272011-04-08 18:41:53 +00006593 << lex.get()->getType() << rex.get()->getType()
6594 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00006595 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006596}
6597
John Wiegley429bb272011-04-08 18:41:53 +00006598QualType Sema::CheckVectorOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00006599 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006600 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00006601 QualType lhsType =
John Wiegley429bb272011-04-08 18:41:53 +00006602 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattnerb77792e2008-07-26 22:17:49 +00006603 QualType rhsType =
John Wiegley429bb272011-04-08 18:41:53 +00006604 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006605
Nate Begemanbe2341d2008-07-14 18:02:46 +00006606 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006607 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00006608 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00006609
Nate Begemanbe2341d2008-07-14 18:02:46 +00006610 // Handle the case of a vector & extvector type of the same size and element
6611 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006612 if (getLangOptions().LaxVectorConversions) {
John McCall183700f2009-09-21 23:43:11 +00006613 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth629f9e42010-08-30 07:36:24 +00006614 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00006615 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006616 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregor26bcf672010-05-19 03:21:00 +00006617 if (lhsType->isExtVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006618 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006619 return lhsType;
6620 }
6621
John Wiegley429bb272011-04-08 18:41:53 +00006622 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006623 return rhsType;
Eric Christophere84f9eb2010-08-26 00:42:16 +00006624 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6625 // If we are allowing lax vector conversions, and LHS and RHS are both
6626 // vectors, the total size only needs to be the same. This is a
6627 // bitcast; no bits are changed but the result type is different.
John Wiegley429bb272011-04-08 18:41:53 +00006628 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Eric Christophere84f9eb2010-08-26 00:42:16 +00006629 return lhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006630 }
Eric Christophere84f9eb2010-08-26 00:42:16 +00006631 }
Chandler Carruth629f9e42010-08-30 07:36:24 +00006632 }
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006633 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006634
Douglas Gregor255210e2010-08-06 10:14:59 +00006635 // Handle the case of equivalent AltiVec and GCC vector types
6636 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6637 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John Wiegley429bb272011-04-08 18:41:53 +00006638 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor255210e2010-08-06 10:14:59 +00006639 return rhsType;
6640 }
6641
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006642 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6643 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6644 bool swapped = false;
6645 if (rhsType->isExtVectorType()) {
6646 swapped = true;
6647 std::swap(rex, lex);
6648 std::swap(rhsType, lhsType);
6649 }
Mike Stump1eb44332009-09-09 15:08:12 +00006650
Nate Begemandde25982009-06-28 19:12:57 +00006651 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00006652 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006653 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00006654 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006655 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6656 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00006657 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006658 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00006659 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006660 if (swapped) std::swap(rex, lex);
6661 return lhsType;
6662 }
6663 }
6664 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6665 rhsType->isRealFloatingType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006666 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6667 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00006668 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006669 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00006670 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006671 if (swapped) std::swap(rex, lex);
6672 return lhsType;
6673 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006674 }
6675 }
Mike Stump1eb44332009-09-09 15:08:12 +00006676
Nate Begemandde25982009-06-28 19:12:57 +00006677 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006678 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley429bb272011-04-08 18:41:53 +00006679 << lex.get()->getType() << rex.get()->getType()
6680 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006681 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006682}
6683
Chris Lattner7ef655a2010-01-12 21:23:57 +00006684QualType Sema::CheckMultiplyDivideOperands(
John Wiegley429bb272011-04-08 18:41:53 +00006685 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
6686 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006687 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006688
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006689 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00006690 if (lex.isInvalid() || rex.isInvalid())
6691 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006692
John Wiegley429bb272011-04-08 18:41:53 +00006693 if (!lex.get()->getType()->isArithmeticType() ||
6694 !rex.get()->getType()->isArithmeticType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00006695 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006696
Chris Lattner7ef655a2010-01-12 21:23:57 +00006697 // Check for division by zero.
6698 if (isDiv &&
John Wiegley429bb272011-04-08 18:41:53 +00006699 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6700 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
6701 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006702
Chris Lattner7ef655a2010-01-12 21:23:57 +00006703 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006704}
6705
Chris Lattner7ef655a2010-01-12 21:23:57 +00006706QualType Sema::CheckRemainderOperands(
John Wiegley429bb272011-04-08 18:41:53 +00006707 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
6708 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6709 if (lex.get()->getType()->hasIntegerRepresentation() &&
6710 rex.get()->getType()->hasIntegerRepresentation())
Daniel Dunbar523aa602009-01-05 22:55:36 +00006711 return CheckVectorOperands(Loc, lex, rex);
6712 return InvalidOperands(Loc, lex, rex);
6713 }
Steve Naroff90045e82007-07-13 23:32:42 +00006714
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006715 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00006716 if (lex.isInvalid() || rex.isInvalid())
6717 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006718
John Wiegley429bb272011-04-08 18:41:53 +00006719 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00006720 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006721
Chris Lattner7ef655a2010-01-12 21:23:57 +00006722 // Check for remainder by zero.
John Wiegley429bb272011-04-08 18:41:53 +00006723 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6724 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
6725 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006726
Chris Lattner7ef655a2010-01-12 21:23:57 +00006727 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006728}
6729
Chris Lattner7ef655a2010-01-12 21:23:57 +00006730QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00006731 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
6732 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006733 QualType compType = CheckVectorOperands(Loc, lex, rex);
6734 if (CompLHSTy) *CompLHSTy = compType;
6735 return compType;
6736 }
Steve Naroff49b45262007-07-13 16:58:59 +00006737
Eli Friedmanab3a8522009-03-28 01:22:36 +00006738 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00006739 if (lex.isInvalid() || rex.isInvalid())
6740 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006741
Reid Spencer5f016e22007-07-11 17:01:13 +00006742 // handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00006743 if (lex.get()->getType()->isArithmeticType() &&
6744 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006745 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006746 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006747 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006748
Eli Friedmand72d16e2008-05-18 18:08:51 +00006749 // Put any potential pointer into PExp
John Wiegley429bb272011-04-08 18:41:53 +00006750 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006751 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00006752 std::swap(PExp, IExp);
6753
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006754 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006755
Eli Friedmand72d16e2008-05-18 18:08:51 +00006756 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00006757 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00006758
Chris Lattnerb5f15622009-04-24 23:50:08 +00006759 // Check for arithmetic on pointers to incomplete types.
6760 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006761 if (getLangOptions().CPlusPlus) {
6762 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00006763 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006764 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006765 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006766
6767 // GNU extension: arithmetic on pointer to void
6768 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00006769 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00006770 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006771 if (getLangOptions().CPlusPlus) {
6772 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00006773 << lex.get()->getType() << lex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00006774 return QualType();
6775 }
6776
6777 // GNU extension: arithmetic on pointer to function
6778 Diag(Loc, diag::ext_gnu_ptr_func_arith)
John Wiegley429bb272011-04-08 18:41:53 +00006779 << lex.get()->getType() << lex.get()->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00006780 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00006781 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00006782 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00006783 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00006784 PExp->getType()->isObjCObjectPointerType()) &&
6785 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00006786 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6787 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006788 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00006789 return QualType();
6790 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00006791 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006792 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006793 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6794 << PointeeTy << PExp->getSourceRange();
6795 return QualType();
6796 }
Mike Stump1eb44332009-09-09 15:08:12 +00006797
Eli Friedmanab3a8522009-03-28 01:22:36 +00006798 if (CompLHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00006799 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman04e83572009-08-20 04:21:42 +00006800 if (LHSTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +00006801 LHSTy = lex.get()->getType();
Eli Friedman04e83572009-08-20 04:21:42 +00006802 if (LHSTy->isPromotableIntegerType())
6803 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00006804 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00006805 *CompLHSTy = LHSTy;
6806 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00006807 return PExp->getType();
6808 }
6809 }
6810
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006811 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006812}
6813
Chris Lattnereca7be62008-04-07 05:30:13 +00006814// C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00006815QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006816 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00006817 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006818 QualType compType = CheckVectorOperands(Loc, lex, rex);
6819 if (CompLHSTy) *CompLHSTy = compType;
6820 return compType;
6821 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006822
Eli Friedmanab3a8522009-03-28 01:22:36 +00006823 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00006824 if (lex.isInvalid() || rex.isInvalid())
6825 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006826
Chris Lattner6e4ab612007-12-09 21:53:25 +00006827 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006828
Chris Lattner6e4ab612007-12-09 21:53:25 +00006829 // Handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00006830 if (lex.get()->getType()->isArithmeticType() &&
6831 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006832 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006833 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006834 }
Mike Stump1eb44332009-09-09 15:08:12 +00006835
Chris Lattner6e4ab612007-12-09 21:53:25 +00006836 // Either ptr - int or ptr - ptr.
John Wiegley429bb272011-04-08 18:41:53 +00006837 if (lex.get()->getType()->isAnyPointerType()) {
6838 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006839
Douglas Gregore7450f52009-03-24 19:52:54 +00006840 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00006841
Douglas Gregore7450f52009-03-24 19:52:54 +00006842 bool ComplainAboutVoid = false;
6843 Expr *ComplainAboutFunc = 0;
6844 if (lpointee->isVoidType()) {
6845 if (getLangOptions().CPlusPlus) {
6846 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00006847 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00006848 return QualType();
6849 }
6850
6851 // GNU C extension: arithmetic on pointer to void
6852 ComplainAboutVoid = true;
6853 } else if (lpointee->isFunctionType()) {
6854 if (getLangOptions().CPlusPlus) {
6855 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00006856 << lex.get()->getType() << lex.get()->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006857 return QualType();
6858 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006859
6860 // GNU C extension: arithmetic on pointer to function
John Wiegley429bb272011-04-08 18:41:53 +00006861 ComplainAboutFunc = lex.get();
Douglas Gregore7450f52009-03-24 19:52:54 +00006862 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00006863 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00006864 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley429bb272011-04-08 18:41:53 +00006865 << lex.get()->getSourceRange()
6866 << lex.get()->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00006867 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006868
Chris Lattnerb5f15622009-04-24 23:50:08 +00006869 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006870 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006871 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley429bb272011-04-08 18:41:53 +00006872 << lpointee << lex.get()->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00006873 return QualType();
6874 }
Mike Stump1eb44332009-09-09 15:08:12 +00006875
Chris Lattner6e4ab612007-12-09 21:53:25 +00006876 // The result type of a pointer-int computation is the pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00006877 if (rex.get()->getType()->isIntegerType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006878 if (ComplainAboutVoid)
6879 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00006880 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00006881 if (ComplainAboutFunc)
6882 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00006883 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00006884 << ComplainAboutFunc->getSourceRange();
6885
John Wiegley429bb272011-04-08 18:41:53 +00006886 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
6887 return lex.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006888 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006889
Chris Lattner6e4ab612007-12-09 21:53:25 +00006890 // Handle pointer-pointer subtractions.
John Wiegley429bb272011-04-08 18:41:53 +00006891 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006892 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006893
Douglas Gregore7450f52009-03-24 19:52:54 +00006894 // RHS must be a completely-type object type.
6895 // Handle the GNU void* extension.
6896 if (rpointee->isVoidType()) {
6897 if (getLangOptions().CPlusPlus) {
6898 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00006899 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00006900 return QualType();
6901 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006902
Douglas Gregore7450f52009-03-24 19:52:54 +00006903 ComplainAboutVoid = true;
6904 } else if (rpointee->isFunctionType()) {
6905 if (getLangOptions().CPlusPlus) {
6906 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00006907 << rex.get()->getType() << rex.get()->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006908 return QualType();
6909 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006910
6911 // GNU extension: arithmetic on pointer to function
6912 if (!ComplainAboutFunc)
John Wiegley429bb272011-04-08 18:41:53 +00006913 ComplainAboutFunc = rex.get();
Douglas Gregore7450f52009-03-24 19:52:54 +00006914 } else if (!rpointee->isDependentType() &&
6915 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00006916 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley429bb272011-04-08 18:41:53 +00006917 << rex.get()->getSourceRange()
6918 << rex.get()->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00006919 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006920
Eli Friedman88d936b2009-05-16 13:54:38 +00006921 if (getLangOptions().CPlusPlus) {
6922 // Pointee types must be the same: C++ [expr.add]
6923 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6924 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley429bb272011-04-08 18:41:53 +00006925 << lex.get()->getType() << rex.get()->getType()
6926 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman88d936b2009-05-16 13:54:38 +00006927 return QualType();
6928 }
6929 } else {
6930 // Pointee types must be compatible C99 6.5.6p3
6931 if (!Context.typesAreCompatible(
6932 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6933 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6934 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley429bb272011-04-08 18:41:53 +00006935 << lex.get()->getType() << rex.get()->getType()
6936 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman88d936b2009-05-16 13:54:38 +00006937 return QualType();
6938 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006939 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006940
Douglas Gregore7450f52009-03-24 19:52:54 +00006941 if (ComplainAboutVoid)
6942 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00006943 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00006944 if (ComplainAboutFunc)
6945 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00006946 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00006947 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006948
John Wiegley429bb272011-04-08 18:41:53 +00006949 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006950 return Context.getPointerDiffType();
6951 }
6952 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006953
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006954 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006955}
6956
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006957static bool isScopedEnumerationType(QualType T) {
6958 if (const EnumType *ET = dyn_cast<EnumType>(T))
6959 return ET->getDecl()->isScoped();
6960 return false;
6961}
6962
John Wiegley429bb272011-04-08 18:41:53 +00006963static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth21206d52011-02-23 23:34:11 +00006964 SourceLocation Loc, unsigned Opc,
6965 QualType LHSTy) {
6966 llvm::APSInt Right;
6967 // Check right/shifter operand
John Wiegley429bb272011-04-08 18:41:53 +00006968 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006969 return;
6970
6971 if (Right.isNegative()) {
John Wiegley429bb272011-04-08 18:41:53 +00006972 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006973 S.PDiag(diag::warn_shift_negative)
John Wiegley429bb272011-04-08 18:41:53 +00006974 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006975 return;
6976 }
6977 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley429bb272011-04-08 18:41:53 +00006978 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006979 if (Right.uge(LeftBits)) {
John Wiegley429bb272011-04-08 18:41:53 +00006980 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006981 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley429bb272011-04-08 18:41:53 +00006982 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006983 return;
6984 }
6985 if (Opc != BO_Shl)
6986 return;
6987
6988 // When left shifting an ICE which is signed, we can check for overflow which
6989 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6990 // integers have defined behavior modulo one more than the maximum value
6991 // representable in the result type, so never warn for those.
6992 llvm::APSInt Left;
John Wiegley429bb272011-04-08 18:41:53 +00006993 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth21206d52011-02-23 23:34:11 +00006994 LHSTy->hasUnsignedIntegerRepresentation())
6995 return;
6996 llvm::APInt ResultBits =
6997 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6998 if (LeftBits.uge(ResultBits))
6999 return;
7000 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7001 Result = Result.shl(Right);
7002
7003 // If we are only missing a sign bit, this is less likely to result in actual
7004 // bugs -- if the result is cast back to an unsigned type, it will have the
7005 // expected value. Thus we place this behind a different warning that can be
7006 // turned off separately if needed.
7007 if (LeftBits == ResultBits - 1) {
7008 S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
7009 << Result.toString(10) << LHSTy
John Wiegley429bb272011-04-08 18:41:53 +00007010 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00007011 return;
7012 }
7013
7014 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7015 << Result.toString(10) << Result.getMinSignedBits() << LHSTy
John Wiegley429bb272011-04-08 18:41:53 +00007016 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00007017}
7018
Chris Lattnereca7be62008-04-07 05:30:13 +00007019// C99 6.5.7
John Wiegley429bb272011-04-08 18:41:53 +00007020QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth21206d52011-02-23 23:34:11 +00007021 unsigned Opc, bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00007022 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley429bb272011-04-08 18:41:53 +00007023 if (!lex.get()->getType()->hasIntegerRepresentation() ||
7024 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007025 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007026
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007027 // C++0x: Don't allow scoped enums. FIXME: Use something better than
7028 // hasIntegerRepresentation() above instead of this.
John Wiegley429bb272011-04-08 18:41:53 +00007029 if (isScopedEnumerationType(lex.get()->getType()) ||
7030 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007031 return InvalidOperands(Loc, lex, rex);
7032 }
7033
Nate Begeman2207d792009-10-25 02:26:48 +00007034 // Vector shifts promote their scalar inputs to vector type.
John Wiegley429bb272011-04-08 18:41:53 +00007035 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Nate Begeman2207d792009-10-25 02:26:48 +00007036 return CheckVectorOperands(Loc, lex, rex);
7037
Chris Lattnerca5eede2007-12-12 05:47:28 +00007038 // Shifts don't perform usual arithmetic conversions, they just do integer
7039 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00007040
John McCall1bc80af2010-12-16 19:28:59 +00007041 // For the LHS, do usual unary conversions, but then reset them away
7042 // if this is a compound assignment.
John Wiegley429bb272011-04-08 18:41:53 +00007043 ExprResult old_lex = lex;
7044 lex = UsualUnaryConversions(lex.take());
7045 if (lex.isInvalid())
7046 return QualType();
7047 QualType LHSTy = lex.get()->getType();
John McCall1bc80af2010-12-16 19:28:59 +00007048 if (isCompAssign) lex = old_lex;
7049
7050 // The RHS is simpler.
John Wiegley429bb272011-04-08 18:41:53 +00007051 rex = UsualUnaryConversions(rex.take());
7052 if (rex.isInvalid())
7053 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007054
Ryan Flynnd0439682009-08-07 16:20:20 +00007055 // Sanity-check shift operands
Chandler Carruth21206d52011-02-23 23:34:11 +00007056 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnd0439682009-08-07 16:20:20 +00007057
Chris Lattnerca5eede2007-12-12 05:47:28 +00007058 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00007059 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007060}
7061
Chandler Carruth99919472010-07-10 12:30:03 +00007062static bool IsWithinTemplateSpecialization(Decl *D) {
7063 if (DeclContext *DC = D->getDeclContext()) {
7064 if (isa<ClassTemplateSpecializationDecl>(DC))
7065 return true;
7066 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7067 return FD->isFunctionTemplateSpecialization();
7068 }
7069 return false;
7070}
7071
Douglas Gregor0c6db942009-05-04 06:07:12 +00007072// C99 6.5.8, C++ [expr.rel]
John Wiegley429bb272011-04-08 18:41:53 +00007073QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00007074 unsigned OpaqueOpc, bool isRelational) {
John McCall2de56d12010-08-25 11:45:40 +00007075 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00007076
Chris Lattner02dd4b12009-12-05 05:40:13 +00007077 // Handle vector comparisons separately.
John Wiegley429bb272011-04-08 18:41:53 +00007078 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007079 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007080
John Wiegley429bb272011-04-08 18:41:53 +00007081 QualType lType = lex.get()->getType();
7082 QualType rType = rex.get()->getType();
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007083
John Wiegley429bb272011-04-08 18:41:53 +00007084 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
7085 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00007086 QualType LHSStrippedType = LHSStripped->getType();
7087 QualType RHSStrippedType = RHSStripped->getType();
7088
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007089
7090
Chandler Carruth543cb652011-02-17 08:37:06 +00007091 // Two different enums will raise a warning when compared.
7092 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
7093 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
7094 if (LHSEnumType->getDecl()->getIdentifier() &&
7095 RHSEnumType->getDecl()->getIdentifier() &&
7096 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
7097 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7098 << LHSStrippedType << RHSStrippedType
John Wiegley429bb272011-04-08 18:41:53 +00007099 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth543cb652011-02-17 08:37:06 +00007100 }
7101 }
7102 }
7103
Douglas Gregor8eee1192010-06-22 22:12:46 +00007104 if (!lType->hasFloatingRepresentation() &&
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00007105 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley429bb272011-04-08 18:41:53 +00007106 !lex.get()->getLocStart().isMacroID() &&
7107 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00007108 // For non-floating point types, check for self-comparisons of the form
7109 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7110 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00007111 //
7112 // NOTE: Don't warn about comparison expressions resulting from macro
7113 // expansion. Also don't warn about comparisons which are only self
7114 // comparisons within a template specialization. The warnings should catch
7115 // obvious cases in the definition of the template anyways. The idea is to
7116 // warn when the typed comparison operator will always evaluate to the same
7117 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00007118 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00007119 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00007120 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00007121 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00007122 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00007123 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00007124 << (Opc == BO_EQ
7125 || Opc == BO_LE
7126 || Opc == BO_GE));
Douglas Gregord64fdd02010-06-08 19:50:34 +00007127 } else if (lType->isArrayType() && rType->isArrayType() &&
7128 !DRL->getDecl()->getType()->isReferenceType() &&
7129 !DRR->getDecl()->getType()->isReferenceType()) {
7130 // what is it always going to eval to?
7131 char always_evals_to;
7132 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007133 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00007134 always_evals_to = 0; // false
7135 break;
John McCall2de56d12010-08-25 11:45:40 +00007136 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00007137 always_evals_to = 1; // true
7138 break;
7139 default:
7140 // best we can say is 'a constant'
7141 always_evals_to = 2; // e.g. array1 <= array2
7142 break;
7143 }
Ted Kremenek351ba912011-02-23 01:52:04 +00007144 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00007145 << 1 // array
7146 << always_evals_to);
7147 }
7148 }
Chandler Carruth99919472010-07-10 12:30:03 +00007149 }
Mike Stump1eb44332009-09-09 15:08:12 +00007150
Chris Lattner55660a72009-03-08 19:39:53 +00007151 if (isa<CastExpr>(LHSStripped))
7152 LHSStripped = LHSStripped->IgnoreParenCasts();
7153 if (isa<CastExpr>(RHSStripped))
7154 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00007155
Chris Lattner55660a72009-03-08 19:39:53 +00007156 // Warn about comparisons against a string constant (unless the other
7157 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00007158 Expr *literalString = 0;
7159 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00007160 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007161 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007162 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00007163 literalString = lex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007164 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00007165 } else if ((isa<StringLiteral>(RHSStripped) ||
7166 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007167 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007168 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00007169 literalString = rex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007170 literalStringStripped = RHSStripped;
7171 }
7172
7173 if (literalString) {
7174 std::string resultComparison;
7175 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007176 case BO_LT: resultComparison = ") < 0"; break;
7177 case BO_GT: resultComparison = ") > 0"; break;
7178 case BO_LE: resultComparison = ") <= 0"; break;
7179 case BO_GE: resultComparison = ") >= 0"; break;
7180 case BO_EQ: resultComparison = ") == 0"; break;
7181 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00007182 default: assert(false && "Invalid comparison operator");
7183 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007184
Ted Kremenek351ba912011-02-23 01:52:04 +00007185 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00007186 PDiag(diag::warn_stringcompare)
7187 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00007188 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00007189 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00007190 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007191
Douglas Gregord64fdd02010-06-08 19:50:34 +00007192 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley429bb272011-04-08 18:41:53 +00007193 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00007194 UsualArithmeticConversions(lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00007195 if (lex.isInvalid() || rex.isInvalid())
7196 return QualType();
7197 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00007198 else {
John Wiegley429bb272011-04-08 18:41:53 +00007199 lex = UsualUnaryConversions(lex.take());
7200 if (lex.isInvalid())
7201 return QualType();
7202
7203 rex = UsualUnaryConversions(rex.take());
7204 if (rex.isInvalid())
7205 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007206 }
7207
John Wiegley429bb272011-04-08 18:41:53 +00007208 lType = lex.get()->getType();
7209 rType = rex.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007210
Douglas Gregor447b69e2008-11-19 03:25:36 +00007211 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00007212 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00007213
Chris Lattnera5937dd2007-08-26 01:18:55 +00007214 if (isRelational) {
7215 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007216 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007217 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00007218 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007219 if (lType->hasFloatingRepresentation())
John Wiegley429bb272011-04-08 18:41:53 +00007220 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007221
Chris Lattnera5937dd2007-08-26 01:18:55 +00007222 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007223 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007224 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007225
John Wiegley429bb272011-04-08 18:41:53 +00007226 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007227 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00007228 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007229 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007230
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007231 // All of the following pointer-related warnings are GCC extensions, except
7232 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00007233 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00007234 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00007235 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00007236 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00007237 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007238
Douglas Gregor0c6db942009-05-04 06:07:12 +00007239 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00007240 if (LCanPointeeTy == RCanPointeeTy)
7241 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007242 if (!isRelational &&
7243 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7244 // Valid unless comparison between non-null pointer and function pointer
7245 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007246 // In a SFINAE context, we treat this as a hard error to maintain
7247 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007248 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7249 && !LHSIsNull && !RHSIsNull) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007250 Diag(Loc,
7251 isSFINAEContext()?
7252 diag::err_typecheck_comparison_of_fptr_to_void
7253 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley429bb272011-04-08 18:41:53 +00007254 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007255
7256 if (isSFINAEContext())
7257 return QualType();
7258
John Wiegley429bb272011-04-08 18:41:53 +00007259 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007260 return ResultTy;
7261 }
7262 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007263
Douglas Gregor0c6db942009-05-04 06:07:12 +00007264 // C++ [expr.rel]p2:
7265 // [...] Pointer conversions (4.10) and qualification
7266 // conversions (4.4) are performed on pointer operands (or on
7267 // a pointer operand and a null pointer constant) to bring
7268 // them to their composite pointer type. [...]
7269 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00007270 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00007271 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007272 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00007273 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007274 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00007275 if (T.isNull()) {
7276 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007277 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00007278 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007279 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007280 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007281 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007282 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00007283 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00007284 }
7285
John Wiegley429bb272011-04-08 18:41:53 +00007286 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7287 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00007288 return ResultTy;
7289 }
Eli Friedman3075e762009-08-23 00:27:47 +00007290 // C99 6.5.9p2 and C99 6.5.8p2
7291 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7292 RCanPointeeTy.getUnqualifiedType())) {
7293 // Valid unless a relational comparison of function pointers
7294 if (isRelational && LCanPointeeTy->isFunctionType()) {
7295 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007296 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007297 }
7298 } else if (!isRelational &&
7299 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7300 // Valid unless comparison between non-null pointer and function pointer
7301 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7302 && !LHSIsNull && !RHSIsNull) {
7303 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley429bb272011-04-08 18:41:53 +00007304 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007305 }
7306 } else {
7307 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007308 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007309 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007310 }
John McCall34d6f932011-03-11 04:25:25 +00007311 if (LCanPointeeTy != RCanPointeeTy) {
7312 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007313 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007314 else
John Wiegley429bb272011-04-08 18:41:53 +00007315 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007316 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007317 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007318 }
Mike Stump1eb44332009-09-09 15:08:12 +00007319
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007320 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007321 // Comparison of nullptr_t with itself.
7322 if (lType->isNullPtrType() && rType->isNullPtrType())
7323 return ResultTy;
7324
Mike Stump1eb44332009-09-09 15:08:12 +00007325 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007326 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007327 if (RHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007328 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00007329 (!isRelational && lType->isMemberPointerType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00007330 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregor443c2122010-08-07 13:36:37 +00007331 lType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007332 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007333 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007334 return ResultTy;
7335 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007336 if (LHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007337 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00007338 (!isRelational && rType->isMemberPointerType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00007339 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregor443c2122010-08-07 13:36:37 +00007340 rType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007341 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007342 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007343 return ResultTy;
7344 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007345
7346 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00007347 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00007348 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7349 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00007350 // In addition, pointers to members can be compared, or a pointer to
7351 // member and a null pointer constant. Pointer to member conversions
7352 // (4.11) and qualification conversions (4.4) are performed to bring
7353 // them to a common type. If one operand is a null pointer constant,
7354 // the common type is the type of the other operand. Otherwise, the
7355 // common type is a pointer to member type similar (4.4) to the type
7356 // of one of the operands, with a cv-qualification signature (4.4)
7357 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00007358 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007359 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00007360 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007361 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00007362 if (T.isNull()) {
7363 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007364 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00007365 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007366 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007367 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007368 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007369 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00007370 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00007371 }
Mike Stump1eb44332009-09-09 15:08:12 +00007372
John Wiegley429bb272011-04-08 18:41:53 +00007373 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7374 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00007375 return ResultTy;
7376 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007377
7378 // Handle scoped enumeration types specifically, since they don't promote
7379 // to integers.
John Wiegley429bb272011-04-08 18:41:53 +00007380 if (lex.get()->getType()->isEnumeralType() &&
7381 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007382 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007383 }
Mike Stump1eb44332009-09-09 15:08:12 +00007384
Steve Naroff1c7d0672008-09-04 15:10:53 +00007385 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00007386 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00007387 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7388 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007389
Steve Naroff1c7d0672008-09-04 15:10:53 +00007390 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007391 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007392 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley429bb272011-04-08 18:41:53 +00007393 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007394 }
John Wiegley429bb272011-04-08 18:41:53 +00007395 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007396 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007397 }
John Wiegley429bb272011-04-08 18:41:53 +00007398
Steve Naroff59f53942008-09-28 01:11:11 +00007399 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00007400 if (!isRelational
7401 && ((lType->isBlockPointerType() && rType->isPointerType())
7402 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007403 if (!LHSIsNull && !RHSIsNull) {
John McCall34d6f932011-03-11 04:25:25 +00007404 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007405 ->getPointeeType()->isVoidType())
John McCall34d6f932011-03-11 04:25:25 +00007406 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007407 ->getPointeeType()->isVoidType())))
7408 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley429bb272011-04-08 18:41:53 +00007409 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007410 }
John McCall34d6f932011-03-11 04:25:25 +00007411 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007412 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007413 else
John Wiegley429bb272011-04-08 18:41:53 +00007414 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007415 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007416 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007417
John McCall34d6f932011-03-11 04:25:25 +00007418 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7419 const PointerType *LPT = lType->getAs<PointerType>();
7420 const PointerType *RPT = rType->getAs<PointerType>();
7421 if (LPT || RPT) {
7422 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7423 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007424
Steve Naroffa8069f12008-11-17 19:49:16 +00007425 if (!LPtrToVoid && !RPtrToVoid &&
7426 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007427 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007428 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00007429 }
John McCall34d6f932011-03-11 04:25:25 +00007430 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007431 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007432 else
John Wiegley429bb272011-04-08 18:41:53 +00007433 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007434 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007435 }
Steve Naroff14108da2009-07-10 23:34:53 +00007436 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007437 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00007438 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007439 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall34d6f932011-03-11 04:25:25 +00007440 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007441 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007442 else
John Wiegley429bb272011-04-08 18:41:53 +00007443 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007444 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007445 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007446 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007447 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7448 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007449 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007450 bool isError = false;
7451 if ((LHSIsNull && lType->isIntegerType()) ||
7452 (RHSIsNull && rType->isIntegerType())) {
7453 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007454 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007455 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007456 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007457 else if (getLangOptions().CPlusPlus) {
7458 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7459 isError = true;
7460 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007461 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007462
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007463 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007464 Diag(Loc, DiagID)
John Wiegley429bb272011-04-08 18:41:53 +00007465 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007466 if (isError)
7467 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007468 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007469
7470 if (lType->isIntegerType())
John Wiegley429bb272011-04-08 18:41:53 +00007471 lex = ImpCastExprToType(lex.take(), rType,
John McCall404cd162010-11-13 01:35:44 +00007472 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007473 else
John Wiegley429bb272011-04-08 18:41:53 +00007474 rex = ImpCastExprToType(rex.take(), lType,
John McCall404cd162010-11-13 01:35:44 +00007475 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007476 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007477 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007478
Steve Naroff39218df2008-09-04 16:56:14 +00007479 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00007480 if (!isRelational && RHSIsNull
7481 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00007482 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007483 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007484 }
Mike Stumpaf199f32009-05-07 18:43:07 +00007485 if (!isRelational && LHSIsNull
7486 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00007487 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007488 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007489 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007490
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007491 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007492}
7493
Nate Begemanbe2341d2008-07-14 18:02:46 +00007494/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007495/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007496/// like a scalar comparison, a vector comparison produces a vector of integer
7497/// types.
John Wiegley429bb272011-04-08 18:41:53 +00007498QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007499 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007500 bool isRelational) {
7501 // Check to make sure we're operating on vectors of the same type and width,
7502 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007503 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007504 if (vType.isNull())
7505 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007506
John Wiegley429bb272011-04-08 18:41:53 +00007507 QualType lType = lex.get()->getType();
7508 QualType rType = rex.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007509
Anton Yartsev7870b132011-03-27 15:36:07 +00007510 // If AltiVec, the comparison results in a numeric type, i.e.
7511 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007512 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007513 return Context.getLogicalOperationType();
7514
Nate Begemanbe2341d2008-07-14 18:02:46 +00007515 // For non-floating point types, check for self-comparisons of the form
7516 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7517 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007518 if (!lType->hasFloatingRepresentation()) {
John Wiegley429bb272011-04-08 18:41:53 +00007519 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
7520 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007521 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007522 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007523 PDiag(diag::warn_comparison_always)
7524 << 0 // self-
7525 << 2 // "a constant"
7526 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007527 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007528
Nate Begemanbe2341d2008-07-14 18:02:46 +00007529 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007530 if (!isRelational && lType->hasFloatingRepresentation()) {
7531 assert (rType->hasFloatingRepresentation());
John Wiegley429bb272011-04-08 18:41:53 +00007532 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007533 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007534
Nate Begemanbe2341d2008-07-14 18:02:46 +00007535 // Return the type for the comparison, which is the same as vector type for
7536 // integer vectors, or an integer type of identical size and number of
7537 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00007538 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00007539 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007540
John McCall183700f2009-09-21 23:43:11 +00007541 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00007542 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00007543 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007544 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00007545 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00007546 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7547
Mike Stumpeed9cac2009-02-19 03:04:26 +00007548 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00007549 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00007550 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7551}
7552
Reid Spencer5f016e22007-07-11 17:01:13 +00007553inline QualType Sema::CheckBitwiseOperands(
John Wiegley429bb272011-04-08 18:41:53 +00007554 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
7555 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
7556 if (lex.get()->getType()->hasIntegerRepresentation() &&
7557 rex.get()->getType()->hasIntegerRepresentation())
Douglas Gregorf6094622010-07-23 15:58:24 +00007558 return CheckVectorOperands(Loc, lex, rex);
7559
7560 return InvalidOperands(Loc, lex, rex);
7561 }
Steve Naroff90045e82007-07-13 23:32:42 +00007562
John Wiegley429bb272011-04-08 18:41:53 +00007563 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
7564 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
7565 if (lexResult.isInvalid() || rexResult.isInvalid())
7566 return QualType();
7567 lex = lexResult.take();
7568 rex = rexResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007569
John Wiegley429bb272011-04-08 18:41:53 +00007570 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
7571 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007572 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007573 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007574}
7575
7576inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley429bb272011-04-08 18:41:53 +00007577 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00007578
7579 // Diagnose cases where the user write a logical and/or but probably meant a
7580 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7581 // is a constant.
John Wiegley429bb272011-04-08 18:41:53 +00007582 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
7583 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Chris Lattner23ef3e42010-07-15 00:26:43 +00007584 // Don't warn in macros.
Chris Lattnerb7690b42010-07-24 01:10:11 +00007585 !Loc.isMacroID()) {
7586 // If the RHS can be constant folded, and if it constant folds to something
7587 // that isn't 0 or 1 (which indicate a potential logical operation that
7588 // happened to fold to true/false) then warn.
7589 Expr::EvalResult Result;
John Wiegley429bb272011-04-08 18:41:53 +00007590 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects &&
Chris Lattnerb7690b42010-07-24 01:10:11 +00007591 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7592 Diag(Loc, diag::warn_logical_instead_of_bitwise)
John Wiegley429bb272011-04-08 18:41:53 +00007593 << rex.get()->getSourceRange()
John McCall2de56d12010-08-25 11:45:40 +00007594 << (Opc == BO_LAnd ? "&&" : "||")
7595 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattnerb7690b42010-07-24 01:10:11 +00007596 }
7597 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007598
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007599 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007600 lex = UsualUnaryConversions(lex.take());
7601 if (lex.isInvalid())
7602 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007603
John Wiegley429bb272011-04-08 18:41:53 +00007604 rex = UsualUnaryConversions(rex.take());
7605 if (rex.isInvalid())
7606 return QualType();
7607
7608 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007609 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007610
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007611 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007612 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007613
John McCall75f7c0f2010-06-04 00:29:51 +00007614 // The following is safe because we only use this method for
7615 // non-overloadable operands.
7616
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007617 // C++ [expr.log.and]p1
7618 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007619 // The operands are both contextually converted to type bool.
John Wiegley429bb272011-04-08 18:41:53 +00007620 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
7621 if (lexRes.isInvalid())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007622 return InvalidOperands(Loc, lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00007623 lex = move(lexRes);
7624
7625 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
7626 if (rexRes.isInvalid())
7627 return InvalidOperands(Loc, lex, rex);
7628 rex = move(rexRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007629
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007630 // C++ [expr.log.and]p2
7631 // C++ [expr.log.or]p2
7632 // The result is a bool.
7633 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007634}
7635
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007636/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7637/// is a read-only property; return true if so. A readonly property expression
7638/// depends on various declarations and thus must be treated specially.
7639///
Mike Stump1eb44332009-09-09 15:08:12 +00007640static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007641 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7642 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00007643 if (PropExpr->isImplicitProperty()) return false;
7644
7645 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7646 QualType BaseType = PropExpr->isSuperReceiver() ?
7647 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007648 PropExpr->getBase()->getType();
7649
John McCall12f78a62010-12-02 01:19:52 +00007650 if (const ObjCObjectPointerType *OPT =
7651 BaseType->getAsObjCInterfacePointerType())
7652 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7653 if (S.isPropertyReadonly(PDecl, IFace))
7654 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007655 }
7656 return false;
7657}
7658
Fariborz Jahanian14086762011-03-28 23:47:18 +00007659static bool IsConstProperty(Expr *E, Sema &S) {
7660 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7661 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7662 if (PropExpr->isImplicitProperty()) return false;
7663
7664 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7665 QualType T = PDecl->getType();
7666 if (T->isReferenceType())
Fariborz Jahanian61750f22011-03-30 16:59:30 +00007667 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanian14086762011-03-28 23:47:18 +00007668 CanQualType CT = S.Context.getCanonicalType(T);
7669 return CT.isConstQualified();
7670 }
7671 return false;
7672}
7673
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007674static bool IsReadonlyMessage(Expr *E, Sema &S) {
7675 if (E->getStmtClass() != Expr::MemberExprClass)
7676 return false;
7677 const MemberExpr *ME = cast<MemberExpr>(E);
7678 NamedDecl *Member = ME->getMemberDecl();
7679 if (isa<FieldDecl>(Member)) {
7680 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7681 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7682 return false;
7683 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7684 }
7685 return false;
7686}
7687
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007688/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7689/// emit an error and return true. If so, return false.
7690static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007691 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007692 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007693 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007694 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7695 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian14086762011-03-28 23:47:18 +00007696 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7697 IsLV = Expr::MLV_Valid;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007698 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7699 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007700 if (IsLV == Expr::MLV_Valid)
7701 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007702
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007703 unsigned Diag = 0;
7704 bool NeedType = false;
7705 switch (IsLV) { // C99 6.5.16p2
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007706 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007707 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007708 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7709 NeedType = true;
7710 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007711 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007712 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7713 NeedType = true;
7714 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007715 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007716 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7717 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007718 case Expr::MLV_Valid:
7719 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007720 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007721 case Expr::MLV_MemberFunction:
7722 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007723 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7724 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007725 case Expr::MLV_IncompleteType:
7726 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007727 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007728 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00007729 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00007730 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007731 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7732 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00007733 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007734 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7735 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007736 case Expr::MLV_ReadonlyProperty:
7737 Diag = diag::error_readonly_property_assignment;
7738 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007739 case Expr::MLV_NoSetterProperty:
7740 Diag = diag::error_nosetter_property_assignment;
7741 break;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007742 case Expr::MLV_InvalidMessageExpression:
7743 Diag = diag::error_readonly_message_assignment;
7744 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007745 case Expr::MLV_SubObjCPropertySetting:
7746 Diag = diag::error_no_subobject_property_setting;
7747 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007748 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007749
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007750 SourceRange Assign;
7751 if (Loc != OrigLoc)
7752 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007753 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007754 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007755 else
Mike Stump1eb44332009-09-09 15:08:12 +00007756 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007757 return true;
7758}
7759
7760
7761
7762// C99 6.5.16.1
John Wiegley429bb272011-04-08 18:41:53 +00007763QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007764 SourceLocation Loc,
7765 QualType CompoundType) {
7766 // Verify that LHS is a modifiable lvalue, and emit error if not.
7767 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007768 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007769
7770 QualType LHSType = LHS->getType();
John Wiegley429bb272011-04-08 18:41:53 +00007771 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007772 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007773 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007774 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007775 // Simple assignment "x = y".
John Wiegley429bb272011-04-08 18:41:53 +00007776 if (LHS->getObjectKind() == OK_ObjCProperty) {
7777 ExprResult LHSResult = Owned(LHS);
7778 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7779 if (LHSResult.isInvalid())
7780 return QualType();
7781 LHS = LHSResult.take();
7782 }
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007783 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007784 if (RHS.isInvalid())
7785 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007786 // Special case of NSObject attributes on c-style pointer types.
7787 if (ConvTy == IncompatiblePointer &&
7788 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007789 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007790 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007791 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007792 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007793
John McCallf89e55a2010-11-18 06:31:45 +00007794 if (ConvTy == Compatible &&
7795 getLangOptions().ObjCNonFragileABI &&
7796 LHSType->isObjCObjectType())
7797 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7798 << LHSType;
7799
Chris Lattner2c156472008-08-21 18:04:13 +00007800 // If the RHS is a unary plus or minus, check to see if they = and + are
7801 // right next to each other. If so, the user may have typo'd "x =+ 4"
7802 // instead of "x += 4".
John Wiegley429bb272011-04-08 18:41:53 +00007803 Expr *RHSCheck = RHS.get();
Chris Lattner2c156472008-08-21 18:04:13 +00007804 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7805 RHSCheck = ICE->getSubExpr();
7806 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007807 if ((UO->getOpcode() == UO_Plus ||
7808 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007809 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007810 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00007811 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7812 // And there is a space or other character before the subexpr of the
7813 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00007814 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7815 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007816 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007817 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007818 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007819 }
Chris Lattner2c156472008-08-21 18:04:13 +00007820 }
7821 } else {
7822 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007823 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007824 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007825
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007826 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007827 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007828 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007829
Chris Lattner8b5dec32010-07-07 06:14:23 +00007830
7831 // Check to see if the destination operand is a dereferenced null pointer. If
7832 // so, and if not volatile-qualified, this is undefined behavior that the
7833 // optimizer will delete, so warn about it. People sometimes try to use this
7834 // to get a deterministic trap and are surprised by clang's behavior. This
7835 // only handles the pattern "*null = whatever", which is a very syntactic
7836 // check.
7837 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCall2de56d12010-08-25 11:45:40 +00007838 if (UO->getOpcode() == UO_Deref &&
Chris Lattner8b5dec32010-07-07 06:14:23 +00007839 UO->getSubExpr()->IgnoreParenCasts()->
7840 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
7841 !UO->getType().isVolatileQualified()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00007842 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7843 PDiag(diag::warn_indirection_through_null)
7844 << UO->getSubExpr()->getSourceRange());
7845 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7846 PDiag(diag::note_indirection_through_null));
Chris Lattner8b5dec32010-07-07 06:14:23 +00007847 }
7848
Ted Kremeneka0125d82011-02-16 01:57:07 +00007849 // Check for trivial buffer overflows.
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007850 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremeneka0125d82011-02-16 01:57:07 +00007851
Reid Spencer5f016e22007-07-11 17:01:13 +00007852 // C99 6.5.16p3: The type of an assignment expression is the type of the
7853 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007854 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007855 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7856 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007857 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007858 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00007859 return (getLangOptions().CPlusPlus
7860 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007861}
7862
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007863// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007864static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007865 SourceLocation Loc) {
John Wiegley429bb272011-04-08 18:41:53 +00007866 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00007867
John McCallfb8721c2011-04-10 19:13:55 +00007868 LHS = S.CheckPlaceholderExpr(LHS.take());
7869 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007870 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007871 return QualType();
7872
John McCallcf2e5062010-10-12 07:14:40 +00007873 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7874 // operands, but not unary promotions.
7875 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007876
John McCallf6a16482010-12-04 03:47:34 +00007877 // So we treat the LHS as a ignored value, and in C++ we allow the
7878 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007879 LHS = S.IgnoredValueConversions(LHS.take());
7880 if (LHS.isInvalid())
7881 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007882
7883 if (!S.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007884 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7885 if (RHS.isInvalid())
7886 return QualType();
7887 if (!RHS.get()->getType()->isVoidType())
7888 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007889 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007890
John Wiegley429bb272011-04-08 18:41:53 +00007891 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007892}
7893
Steve Naroff49b45262007-07-13 16:58:59 +00007894/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7895/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007896static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7897 ExprValueKind &VK,
7898 SourceLocation OpLoc,
7899 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007900 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007901 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007902
Chris Lattner3528d352008-11-21 07:05:48 +00007903 QualType ResType = Op->getType();
7904 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007905
John McCall09431682010-11-18 19:01:18 +00007906 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007907 // Decrement of bool is not allowed.
7908 if (!isInc) {
John McCall09431682010-11-18 19:01:18 +00007909 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007910 return QualType();
7911 }
7912 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007913 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007914 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007915 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007916 } else if (ResType->isAnyPointerType()) {
7917 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00007918
Chris Lattner3528d352008-11-21 07:05:48 +00007919 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00007920 if (PointeeTy->isVoidType()) {
John McCall09431682010-11-18 19:01:18 +00007921 if (S.getLangOptions().CPlusPlus) {
7922 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00007923 << Op->getSourceRange();
7924 return QualType();
7925 }
7926
7927 // Pointer to void is a GNU extension in C.
John McCall09431682010-11-18 19:01:18 +00007928 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00007929 } else if (PointeeTy->isFunctionType()) {
John McCall09431682010-11-18 19:01:18 +00007930 if (S.getLangOptions().CPlusPlus) {
7931 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00007932 << Op->getType() << Op->getSourceRange();
7933 return QualType();
7934 }
7935
John McCall09431682010-11-18 19:01:18 +00007936 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00007937 << ResType << Op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007938 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7939 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00007940 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00007941 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007942 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007943 // Diagnose bad cases where we step over interface counts.
John McCall09431682010-11-18 19:01:18 +00007944 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7945 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007946 << PointeeTy << Op->getSourceRange();
7947 return QualType();
7948 }
Eli Friedman5b088a12010-01-03 00:20:48 +00007949 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007950 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007951 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007952 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007953 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007954 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007955 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007956 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7957 isInc, isPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00007958 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7959 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007960 } else {
John McCall09431682010-11-18 19:01:18 +00007961 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00007962 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007963 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007964 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007965 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007966 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007967 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007968 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007969 // In C++, a prefix increment is the same type as the operand. Otherwise
7970 // (in C or with postfix), the increment is the unqualified type of the
7971 // operand.
John McCall09431682010-11-18 19:01:18 +00007972 if (isPrefix && S.getLangOptions().CPlusPlus) {
7973 VK = VK_LValue;
7974 return ResType;
7975 } else {
7976 VK = VK_RValue;
7977 return ResType.getUnqualifiedType();
7978 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007979}
7980
John Wiegley429bb272011-04-08 18:41:53 +00007981ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCallf6a16482010-12-04 03:47:34 +00007982 assert(E->getValueKind() == VK_LValue &&
7983 E->getObjectKind() == OK_ObjCProperty);
7984 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7985
7986 ExprValueKind VK = VK_RValue;
7987 if (PRE->isImplicitProperty()) {
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007988 if (const ObjCMethodDecl *GetterMethod =
7989 PRE->getImplicitPropertyGetter()) {
7990 QualType Result = GetterMethod->getResultType();
7991 VK = Expr::getValueKindForType(Result);
7992 }
7993 else {
7994 Diag(PRE->getLocation(), diag::err_getter_not_found)
7995 << PRE->getBase()->getType();
7996 }
John McCallf6a16482010-12-04 03:47:34 +00007997 }
7998
7999 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
8000 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00008001
8002 ExprResult Result = MaybeBindToTemporary(E);
8003 if (!Result.isInvalid())
8004 E = Result.take();
John Wiegley429bb272011-04-08 18:41:53 +00008005
8006 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00008007}
8008
John Wiegley429bb272011-04-08 18:41:53 +00008009void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
8010 assert(LHS.get()->getValueKind() == VK_LValue &&
8011 LHS.get()->getObjectKind() == OK_ObjCProperty);
8012 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCallf6a16482010-12-04 03:47:34 +00008013
John Wiegley429bb272011-04-08 18:41:53 +00008014 if (PropRef->isImplicitProperty()) {
John McCallf6a16482010-12-04 03:47:34 +00008015 // If using property-dot syntax notation for assignment, and there is a
8016 // setter, RHS expression is being passed to the setter argument. So,
8017 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley429bb272011-04-08 18:41:53 +00008018 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCallf6a16482010-12-04 03:47:34 +00008019 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
8020 LHSTy = (*P)->getType();
8021
8022 // Otherwise, if the getter returns an l-value, just call that.
8023 } else {
John Wiegley429bb272011-04-08 18:41:53 +00008024 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCallf6a16482010-12-04 03:47:34 +00008025 ExprValueKind VK = Expr::getValueKindForType(Result);
8026 if (VK == VK_LValue) {
John Wiegley429bb272011-04-08 18:41:53 +00008027 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
8028 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCallf6a16482010-12-04 03:47:34 +00008029 return;
John McCall12f78a62010-12-02 01:19:52 +00008030 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008031 }
John McCallf6a16482010-12-04 03:47:34 +00008032 }
8033
8034 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008035 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00008036 InitializedEntity::InitializeParameter(Context, LHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00008037 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008038 if (!ArgE.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00008039 RHS = ArgE;
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008040 }
8041}
8042
8043
Anders Carlsson369dee42008-02-01 07:15:58 +00008044/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00008045/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008046/// where the declaration is needed for type checking. We only need to
8047/// handle cases when the expression references a function designator
8048/// or is an lvalue. Here are some examples:
8049/// - &(x) => x
8050/// - &*****f => f for f a function designator.
8051/// - &s.xx => s
8052/// - &s.zz[1].yy -> s, if zz is an array
8053/// - *(x + 1) -> x, if x is an array
8054/// - &"123"[2] -> 0
8055/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00008056static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00008057 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00008058 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00008059 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00008060 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00008061 // If this is an arrow operator, the address is an offset from
8062 // the base's value, so the object the base refers to is
8063 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00008064 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00008065 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00008066 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00008067 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00008068 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00008069 // FIXME: This code shouldn't be necessary! We should catch the implicit
8070 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00008071 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8072 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8073 if (ICE->getSubExpr()->getType()->isArrayType())
8074 return getPrimaryDecl(ICE->getSubExpr());
8075 }
8076 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00008077 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008078 case Stmt::UnaryOperatorClass: {
8079 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008080
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008081 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00008082 case UO_Real:
8083 case UO_Imag:
8084 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008085 return getPrimaryDecl(UO->getSubExpr());
8086 default:
8087 return 0;
8088 }
8089 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008090 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00008091 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00008092 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00008093 // If the result of an implicit cast is an l-value, we care about
8094 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00008095 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00008096 default:
8097 return 0;
8098 }
8099}
8100
8101/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00008102/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00008103/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008104/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00008105/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008106/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00008107/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00008108static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
8109 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00008110 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008111 return S.Context.DependentTy;
8112 if (OrigOp->getType() == S.Context.OverloadTy)
8113 return S.Context.OverloadTy;
John McCall755d8492011-04-12 00:42:48 +00008114 if (OrigOp->getType() == S.Context.UnknownAnyTy)
8115 return S.Context.UnknownAnyTy;
John McCall9c72c602010-08-27 09:08:28 +00008116
John McCall755d8492011-04-12 00:42:48 +00008117 assert(!OrigOp->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00008118
John McCall9c72c602010-08-27 09:08:28 +00008119 // Make sure to ignore parentheses in subsequent checks
8120 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00008121
John McCall09431682010-11-18 19:01:18 +00008122 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00008123 // Implement C99-only parts of addressof rules.
8124 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00008125 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00008126 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8127 // (assuming the deref expression is valid).
8128 return uOp->getSubExpr()->getType();
8129 }
8130 // Technically, there should be a check for array subscript
8131 // expressions here, but the result of one is always an lvalue anyway.
8132 }
John McCall5808ce42011-02-03 08:15:49 +00008133 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00008134 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00008135
Fariborz Jahanian077f4902011-03-26 19:48:30 +00008136 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00008137 bool sfinae = S.isSFINAEContext();
8138 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8139 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00008140 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00008141 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00008142 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00008143 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008144 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00008145 } else if (lval == Expr::LV_MemberFunction) {
8146 // If it's an instance method, make a member pointer.
8147 // The expression must have exactly the form &A::foo.
8148
8149 // If the underlying expression isn't a decl ref, give up.
8150 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008151 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008152 << OrigOp->getSourceRange();
8153 return QualType();
8154 }
8155 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8156 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8157
8158 // The id-expression was parenthesized.
8159 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00008160 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008161 << OrigOp->getSourceRange();
8162
8163 // The method was named without a qualifier.
8164 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00008165 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008166 << op->getSourceRange();
8167 }
8168
John McCall09431682010-11-18 19:01:18 +00008169 return S.Context.getMemberPointerType(op->getType(),
8170 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00008171 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00008172 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008173 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00008174 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00008175 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00008176 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008177 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00008178 return QualType();
8179 }
John McCall7eb0a9e2010-11-24 05:12:34 +00008180 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008181 // The operand cannot be a bit-field
John McCall09431682010-11-18 19:01:18 +00008182 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman23d58ce2009-04-20 08:23:18 +00008183 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00008184 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00008185 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00008186 // The operand cannot be an element of a vector
John McCall09431682010-11-18 19:01:18 +00008187 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00008188 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00008189 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00008190 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00008191 // cannot take address of a property expression.
John McCall09431682010-11-18 19:01:18 +00008192 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian0337f212009-07-07 18:50:52 +00008193 << "property expression" << op->getSourceRange();
8194 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00008195 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00008196 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00008197 // with the register storage-class specifier.
8198 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00008199 // in C++ it is not error to take address of a register
8200 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00008201 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00008202 !S.getLangOptions().CPlusPlus) {
8203 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008204 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00008205 return QualType();
8206 }
John McCallba135432009-11-21 08:51:07 +00008207 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00008208 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00008209 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00008210 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00008211 // Could be a pointer to member, though, if there is an explicit
8212 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00008213 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00008214 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008215 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00008216 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00008217 S.Diag(OpLoc,
8218 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00008219 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008220 return QualType();
8221 }
Mike Stump1eb44332009-09-09 15:08:12 +00008222
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00008223 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8224 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00008225 return S.Context.getMemberPointerType(op->getType(),
8226 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008227 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00008228 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00008229 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00008230 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00008231 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00008232
Eli Friedman441cf102009-05-16 23:27:50 +00008233 if (lval == Expr::LV_IncompleteVoidType) {
8234 // Taking the address of a void variable is technically illegal, but we
8235 // allow it in cases which are otherwise valid.
8236 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00008237 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00008238 }
8239
Reid Spencer5f016e22007-07-11 17:01:13 +00008240 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00008241 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00008242 return S.Context.getObjCObjectPointerType(op->getType());
8243 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008244}
8245
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008246/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00008247static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8248 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00008249 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008250 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008251
John Wiegley429bb272011-04-08 18:41:53 +00008252 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8253 if (ConvResult.isInvalid())
8254 return QualType();
8255 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008256 QualType OpTy = Op->getType();
8257 QualType Result;
8258
8259 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8260 // is an incomplete type or void. It would be possible to warn about
8261 // dereferencing a void pointer, but it's completely well-defined, and such a
8262 // warning is unlikely to catch any mistakes.
8263 if (const PointerType *PT = OpTy->getAs<PointerType>())
8264 Result = PT->getPointeeType();
8265 else if (const ObjCObjectPointerType *OPT =
8266 OpTy->getAs<ObjCObjectPointerType>())
8267 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008268 else {
John McCallfb8721c2011-04-10 19:13:55 +00008269 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008270 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008271 if (PR.take() != Op)
8272 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008273 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008274
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008275 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008276 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008277 << OpTy << Op->getSourceRange();
8278 return QualType();
8279 }
John McCall09431682010-11-18 19:01:18 +00008280
8281 // Dereferences are usually l-values...
8282 VK = VK_LValue;
8283
8284 // ...except that certain expressions are never l-values in C.
8285 if (!S.getLangOptions().CPlusPlus &&
8286 IsCForbiddenLValueType(S.Context, Result))
8287 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008288
8289 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008290}
8291
John McCall2de56d12010-08-25 11:45:40 +00008292static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008293 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008294 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008295 switch (Kind) {
8296 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008297 case tok::periodstar: Opc = BO_PtrMemD; break;
8298 case tok::arrowstar: Opc = BO_PtrMemI; break;
8299 case tok::star: Opc = BO_Mul; break;
8300 case tok::slash: Opc = BO_Div; break;
8301 case tok::percent: Opc = BO_Rem; break;
8302 case tok::plus: Opc = BO_Add; break;
8303 case tok::minus: Opc = BO_Sub; break;
8304 case tok::lessless: Opc = BO_Shl; break;
8305 case tok::greatergreater: Opc = BO_Shr; break;
8306 case tok::lessequal: Opc = BO_LE; break;
8307 case tok::less: Opc = BO_LT; break;
8308 case tok::greaterequal: Opc = BO_GE; break;
8309 case tok::greater: Opc = BO_GT; break;
8310 case tok::exclaimequal: Opc = BO_NE; break;
8311 case tok::equalequal: Opc = BO_EQ; break;
8312 case tok::amp: Opc = BO_And; break;
8313 case tok::caret: Opc = BO_Xor; break;
8314 case tok::pipe: Opc = BO_Or; break;
8315 case tok::ampamp: Opc = BO_LAnd; break;
8316 case tok::pipepipe: Opc = BO_LOr; break;
8317 case tok::equal: Opc = BO_Assign; break;
8318 case tok::starequal: Opc = BO_MulAssign; break;
8319 case tok::slashequal: Opc = BO_DivAssign; break;
8320 case tok::percentequal: Opc = BO_RemAssign; break;
8321 case tok::plusequal: Opc = BO_AddAssign; break;
8322 case tok::minusequal: Opc = BO_SubAssign; break;
8323 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8324 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8325 case tok::ampequal: Opc = BO_AndAssign; break;
8326 case tok::caretequal: Opc = BO_XorAssign; break;
8327 case tok::pipeequal: Opc = BO_OrAssign; break;
8328 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008329 }
8330 return Opc;
8331}
8332
John McCall2de56d12010-08-25 11:45:40 +00008333static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008334 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008335 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008336 switch (Kind) {
8337 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008338 case tok::plusplus: Opc = UO_PreInc; break;
8339 case tok::minusminus: Opc = UO_PreDec; break;
8340 case tok::amp: Opc = UO_AddrOf; break;
8341 case tok::star: Opc = UO_Deref; break;
8342 case tok::plus: Opc = UO_Plus; break;
8343 case tok::minus: Opc = UO_Minus; break;
8344 case tok::tilde: Opc = UO_Not; break;
8345 case tok::exclaim: Opc = UO_LNot; break;
8346 case tok::kw___real: Opc = UO_Real; break;
8347 case tok::kw___imag: Opc = UO_Imag; break;
8348 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008349 }
8350 return Opc;
8351}
8352
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008353/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8354/// This warning is only emitted for builtin assignment operations. It is also
8355/// suppressed in the event of macro expansions.
8356static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8357 SourceLocation OpLoc) {
8358 if (!S.ActiveTemplateInstantiations.empty())
8359 return;
8360 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8361 return;
8362 lhs = lhs->IgnoreParenImpCasts();
8363 rhs = rhs->IgnoreParenImpCasts();
8364 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8365 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8366 if (!LeftDeclRef || !RightDeclRef ||
8367 LeftDeclRef->getLocation().isMacroID() ||
8368 RightDeclRef->getLocation().isMacroID())
8369 return;
8370 const ValueDecl *LeftDecl =
8371 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8372 const ValueDecl *RightDecl =
8373 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8374 if (LeftDecl != RightDecl)
8375 return;
8376 if (LeftDecl->getType().isVolatileQualified())
8377 return;
8378 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8379 if (RefTy->getPointeeType().isVolatileQualified())
8380 return;
8381
8382 S.Diag(OpLoc, diag::warn_self_assignment)
8383 << LeftDeclRef->getType()
8384 << lhs->getSourceRange() << rhs->getSourceRange();
8385}
8386
Douglas Gregoreaebc752008-11-06 23:29:22 +00008387/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8388/// operator @p Opc at location @c TokLoc. This routine only supports
8389/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008390ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008391 BinaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008392 Expr *lhsExpr, Expr *rhsExpr) {
8393 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008394 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008395 // The following two variables are used for compound assignment operators
8396 QualType CompLHSTy; // Type of LHS after promotions for computation
8397 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008398 ExprValueKind VK = VK_RValue;
8399 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008400
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008401 // Check if a 'foo<int>' involved in a binary op, identifies a single
8402 // function unambiguously (i.e. an lvalue ala 13.4)
8403 // But since an assignment can trigger target based overload, exclude it in
8404 // our blind search. i.e:
8405 // template<class T> void f(); template<class T, class U> void f(U);
8406 // f<int> == 0; // resolve f<int> blindly
8407 // void (*p)(int); p = f<int>; // resolve f<int> using target
8408 if (Opc != BO_Assign) {
John McCallfb8721c2011-04-10 19:13:55 +00008409 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008410 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008411 lhs = move(resolvedLHS);
John McCall1de4d4e2011-04-07 08:22:57 +00008412
John McCallfb8721c2011-04-10 19:13:55 +00008413 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008414 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008415 rhs = move(resolvedRHS);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008416 }
8417
Douglas Gregoreaebc752008-11-06 23:29:22 +00008418 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008419 case BO_Assign:
John Wiegley429bb272011-04-08 18:41:53 +00008420 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00008421 if (getLangOptions().CPlusPlus &&
John Wiegley429bb272011-04-08 18:41:53 +00008422 lhs.get()->getObjectKind() != OK_ObjCProperty) {
8423 VK = lhs.get()->getValueKind();
8424 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008425 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008426 if (!ResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00008427 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008428 break;
John McCall2de56d12010-08-25 11:45:40 +00008429 case BO_PtrMemD:
8430 case BO_PtrMemI:
John McCallf89e55a2010-11-18 06:31:45 +00008431 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008432 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008433 break;
John McCall2de56d12010-08-25 11:45:40 +00008434 case BO_Mul:
8435 case BO_Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00008436 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008437 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008438 break;
John McCall2de56d12010-08-25 11:45:40 +00008439 case BO_Rem:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008440 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
8441 break;
John McCall2de56d12010-08-25 11:45:40 +00008442 case BO_Add:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008443 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
8444 break;
John McCall2de56d12010-08-25 11:45:40 +00008445 case BO_Sub:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008446 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
8447 break;
John McCall2de56d12010-08-25 11:45:40 +00008448 case BO_Shl:
8449 case BO_Shr:
Chandler Carruth21206d52011-02-23 23:34:11 +00008450 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008451 break;
John McCall2de56d12010-08-25 11:45:40 +00008452 case BO_LE:
8453 case BO_LT:
8454 case BO_GE:
8455 case BO_GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00008456 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008457 break;
John McCall2de56d12010-08-25 11:45:40 +00008458 case BO_EQ:
8459 case BO_NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00008460 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008461 break;
John McCall2de56d12010-08-25 11:45:40 +00008462 case BO_And:
8463 case BO_Xor:
8464 case BO_Or:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008465 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8466 break;
John McCall2de56d12010-08-25 11:45:40 +00008467 case BO_LAnd:
8468 case BO_LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00008469 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008470 break;
John McCall2de56d12010-08-25 11:45:40 +00008471 case BO_MulAssign:
8472 case BO_DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00008473 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008474 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008475 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00008476 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8477 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008478 break;
John McCall2de56d12010-08-25 11:45:40 +00008479 case BO_RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008480 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
8481 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00008482 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8483 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008484 break;
John McCall2de56d12010-08-25 11:45:40 +00008485 case BO_AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008486 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00008487 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8488 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008489 break;
John McCall2de56d12010-08-25 11:45:40 +00008490 case BO_SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008491 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00008492 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8493 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008494 break;
John McCall2de56d12010-08-25 11:45:40 +00008495 case BO_ShlAssign:
8496 case BO_ShrAssign:
Chandler Carruth21206d52011-02-23 23:34:11 +00008497 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008498 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00008499 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8500 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008501 break;
John McCall2de56d12010-08-25 11:45:40 +00008502 case BO_AndAssign:
8503 case BO_XorAssign:
8504 case BO_OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008505 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8506 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00008507 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8508 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008509 break;
John McCall2de56d12010-08-25 11:45:40 +00008510 case BO_Comma:
John McCall09431682010-11-18 19:01:18 +00008511 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00008512 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
8513 VK = rhs.get()->getValueKind();
8514 OK = rhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008515 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008516 break;
8517 }
John Wiegley429bb272011-04-08 18:41:53 +00008518 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008519 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00008520 if (CompResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00008521 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
8522 ResultTy, VK, OK, OpLoc));
8523 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008524 VK = VK_LValue;
John Wiegley429bb272011-04-08 18:41:53 +00008525 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008526 }
John Wiegley429bb272011-04-08 18:41:53 +00008527 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
8528 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00008529 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008530}
8531
Sebastian Redlaee3c932009-10-27 12:10:02 +00008532/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8533/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008534static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8535 const PartialDiagnostic &PD,
Douglas Gregor55b38842010-04-14 16:09:52 +00008536 const PartialDiagnostic &FirstNote,
8537 SourceRange FirstParenRange,
8538 const PartialDiagnostic &SecondNote,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008539 SourceRange SecondParenRange) {
Douglas Gregor55b38842010-04-14 16:09:52 +00008540 Self.Diag(Loc, PD);
8541
8542 if (!FirstNote.getDiagID())
8543 return;
8544
8545 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8546 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8547 // We can't display the parentheses, so just return.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008548 return;
8549 }
8550
Douglas Gregor55b38842010-04-14 16:09:52 +00008551 Self.Diag(Loc, FirstNote)
8552 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregor849b2432010-03-31 17:46:05 +00008553 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008554
Douglas Gregor55b38842010-04-14 16:09:52 +00008555 if (!SecondNote.getDiagID())
Douglas Gregor827feec2010-01-08 00:20:23 +00008556 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008557
Douglas Gregor827feec2010-01-08 00:20:23 +00008558 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8559 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8560 // We can't display the parentheses, so just dig the
8561 // warning/error and return.
Douglas Gregor55b38842010-04-14 16:09:52 +00008562 Self.Diag(Loc, SecondNote);
Douglas Gregor827feec2010-01-08 00:20:23 +00008563 return;
8564 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008565
Douglas Gregor55b38842010-04-14 16:09:52 +00008566 Self.Diag(Loc, SecondNote)
Douglas Gregor849b2432010-03-31 17:46:05 +00008567 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8568 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008569}
8570
Sebastian Redlaee3c932009-10-27 12:10:02 +00008571/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8572/// operators are mixed in a way that suggests that the programmer forgot that
8573/// comparison operators have higher precedence. The most typical example of
8574/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008575static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008576 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00008577 typedef BinaryOperator BinOp;
8578 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8579 rhsopc = static_cast<BinOp::Opcode>(-1);
8580 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008581 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00008582 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008583 rhsopc = BO->getOpcode();
8584
8585 // Subs are not binary operators.
8586 if (lhsopc == -1 && rhsopc == -1)
8587 return;
8588
8589 // Bitwise operations are sometimes used as eager logical ops.
8590 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00008591 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8592 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008593 return;
8594
Sebastian Redlaee3c932009-10-27 12:10:02 +00008595 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008596 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008597 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00008598 << SourceRange(lhs->getLocStart(), OpLoc)
8599 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008600 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00008601 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00008602 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
8603 Self.PDiag(diag::note_precedence_bitwise_silence)
8604 << BinOp::getOpcodeStr(lhsopc),
8605 lhs->getSourceRange());
Sebastian Redlaee3c932009-10-27 12:10:02 +00008606 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008607 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008608 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00008609 << SourceRange(OpLoc, rhs->getLocEnd())
8610 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008611 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00008612 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00008613 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
8614 Self.PDiag(diag::note_precedence_bitwise_silence)
8615 << BinOp::getOpcodeStr(rhsopc),
8616 rhs->getSourceRange());
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008617}
8618
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008619/// \brief It accepts a '&&' expr that is inside a '||' one.
8620/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8621/// in parentheses.
8622static void
8623EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8624 Expr *E) {
8625 assert(isa<BinaryOperator>(E) &&
8626 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
8627 SuggestParentheses(Self, OpLoc,
8628 Self.PDiag(diag::warn_logical_and_in_logical_or)
8629 << E->getSourceRange(),
8630 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8631 E->getSourceRange(),
8632 Self.PDiag(0), SourceRange());
8633}
8634
8635/// \brief Returns true if the given expression can be evaluated as a constant
8636/// 'true'.
8637static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8638 bool Res;
8639 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8640}
8641
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008642/// \brief Returns true if the given expression can be evaluated as a constant
8643/// 'false'.
8644static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8645 bool Res;
8646 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8647}
8648
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008649/// \brief Look for '&&' in the left hand of a '||' expr.
8650static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008651 Expr *OrLHS, Expr *OrRHS) {
8652 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008653 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008654 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8655 if (EvaluatesAsFalse(S, OrRHS))
8656 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008657 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8658 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8659 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8660 } else if (Bop->getOpcode() == BO_LOr) {
8661 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8662 // If it's "a || b && 1 || c" we didn't warn earlier for
8663 // "a || b && 1", but warn now.
8664 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8665 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8666 }
8667 }
8668 }
8669}
8670
8671/// \brief Look for '&&' in the right hand of a '||' expr.
8672static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008673 Expr *OrLHS, Expr *OrRHS) {
8674 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008675 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008676 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8677 if (EvaluatesAsFalse(S, OrLHS))
8678 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008679 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8680 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8681 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008682 }
8683 }
8684}
8685
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008686/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008687/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008688static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008689 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008690 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008691 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008692 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8693
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008694 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8695 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008696 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008697 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8698 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008699 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008700}
8701
Reid Spencer5f016e22007-07-11 17:01:13 +00008702// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008703ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008704 tok::TokenKind Kind,
8705 Expr *lhs, Expr *rhs) {
8706 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Narofff69936d2007-09-16 03:34:24 +00008707 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8708 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008709
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008710 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8711 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8712
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008713 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8714}
8715
John McCall60d7b3a2010-08-24 06:29:42 +00008716ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008717 BinaryOperatorKind Opc,
8718 Expr *lhs, Expr *rhs) {
John McCall01b2e4e2010-12-06 05:26:58 +00008719 if (getLangOptions().CPlusPlus) {
8720 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008721
John McCall01b2e4e2010-12-06 05:26:58 +00008722 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8723 UseBuiltinOperator = false;
8724 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8725 UseBuiltinOperator = true;
8726 } else {
8727 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8728 !rhs->getType()->isOverloadableType();
8729 }
8730
8731 if (!UseBuiltinOperator) {
8732 // Find all of the overloaded operators visible from this
8733 // point. We perform both an operator-name lookup from the local
8734 // scope and an argument-dependent lookup based on the types of
8735 // the arguments.
8736 UnresolvedSet<16> Functions;
8737 OverloadedOperatorKind OverOp
8738 = BinaryOperator::getOverloadedOperator(Opc);
8739 if (S && OverOp != OO_None)
8740 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8741 Functions);
8742
8743 // Build the (potentially-overloaded, potentially-dependent)
8744 // binary operation.
8745 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8746 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008747 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008748
Douglas Gregoreaebc752008-11-06 23:29:22 +00008749 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008750 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00008751}
8752
John McCall60d7b3a2010-08-24 06:29:42 +00008753ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008754 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008755 Expr *InputExpr) {
8756 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008757 ExprValueKind VK = VK_RValue;
8758 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008759 QualType resultType;
8760 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008761 case UO_PreInc:
8762 case UO_PreDec:
8763 case UO_PostInc:
8764 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008765 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008766 Opc == UO_PreInc ||
8767 Opc == UO_PostInc,
8768 Opc == UO_PreInc ||
8769 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008770 break;
John McCall2de56d12010-08-25 11:45:40 +00008771 case UO_AddrOf:
John Wiegley429bb272011-04-08 18:41:53 +00008772 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008773 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008774 case UO_Deref: {
John McCallfb8721c2011-04-10 19:13:55 +00008775 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008776 if (!resolved.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008777 Input = move(resolved);
8778 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8779 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008780 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008781 }
John McCall2de56d12010-08-25 11:45:40 +00008782 case UO_Plus:
8783 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008784 Input = UsualUnaryConversions(Input.take());
8785 if (Input.isInvalid()) return ExprError();
8786 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008787 if (resultType->isDependentType())
8788 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008789 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8790 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008791 break;
8792 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8793 resultType->isEnumeralType())
8794 break;
8795 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008796 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008797 resultType->isPointerType())
8798 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008799 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008800 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008801 if (Input.isInvalid()) return ExprError();
8802 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008803 }
Douglas Gregor74253732008-11-19 15:42:04 +00008804
Sebastian Redl0eb23302009-01-19 00:08:26 +00008805 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008806 << resultType << Input.get()->getSourceRange());
8807
John McCall2de56d12010-08-25 11:45:40 +00008808 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008809 Input = UsualUnaryConversions(Input.take());
8810 if (Input.isInvalid()) return ExprError();
8811 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008812 if (resultType->isDependentType())
8813 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008814 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8815 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8816 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008817 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008818 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008819 else if (resultType->hasIntegerRepresentation())
8820 break;
8821 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008822 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008823 if (Input.isInvalid()) return ExprError();
8824 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008825 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008826 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008827 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008828 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008829 break;
John Wiegley429bb272011-04-08 18:41:53 +00008830
John McCall2de56d12010-08-25 11:45:40 +00008831 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008832 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008833 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8834 if (Input.isInvalid()) return ExprError();
8835 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008836 if (resultType->isDependentType())
8837 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008838 if (resultType->isScalarType()) {
8839 // C99 6.5.3.3p1: ok, fallthrough;
8840 if (Context.getLangOptions().CPlusPlus) {
8841 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8842 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008843 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8844 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008845 }
John McCall2cd11fe2010-10-12 02:09:17 +00008846 } else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008847 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008848 if (Input.isInvalid()) return ExprError();
8849 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008850 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008851 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008852 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008853 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008854
Reid Spencer5f016e22007-07-11 17:01:13 +00008855 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008856 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008857 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008858 break;
John McCall2de56d12010-08-25 11:45:40 +00008859 case UO_Real:
8860 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008861 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00008862 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley429bb272011-04-08 18:41:53 +00008863 if (Input.isInvalid()) return ExprError();
8864 if (Input.get()->getValueKind() != VK_RValue &&
8865 Input.get()->getObjectKind() == OK_Ordinary)
8866 VK = Input.get()->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00008867 break;
John McCall2de56d12010-08-25 11:45:40 +00008868 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008869 resultType = Input.get()->getType();
8870 VK = Input.get()->getValueKind();
8871 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008872 break;
8873 }
John Wiegley429bb272011-04-08 18:41:53 +00008874 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008875 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008876
John Wiegley429bb272011-04-08 18:41:53 +00008877 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008878 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008879}
8880
John McCall60d7b3a2010-08-24 06:29:42 +00008881ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008882 UnaryOperatorKind Opc,
8883 Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00008884 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00008885 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008886 // Find all of the overloaded operators visible from this
8887 // point. We perform both an operator-name lookup from the local
8888 // scope and an argument-dependent lookup based on the types of
8889 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008890 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008891 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008892 if (S && OverOp != OO_None)
8893 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8894 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008895
John McCall9ae2f072010-08-23 23:25:46 +00008896 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008897 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008898
John McCall9ae2f072010-08-23 23:25:46 +00008899 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008900}
8901
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008902// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008903ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008904 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008905 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008906}
8907
Steve Naroff1b273c42007-09-16 14:56:35 +00008908/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008909ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008910 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008911 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008912 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008913 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008914 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008915}
8916
John McCall60d7b3a2010-08-24 06:29:42 +00008917ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008918Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008919 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008920 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8921 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8922
Douglas Gregordd8f5692010-03-10 04:54:39 +00008923 bool isFileScope
8924 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008925 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008926 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008927
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008928 // FIXME: there are a variety of strange constraints to enforce here, for
8929 // example, it is not possible to goto into a stmt expression apparently.
8930 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008931
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008932 // If there are sub stmts in the compound stmt, take the type of the last one
8933 // as the type of the stmtexpr.
8934 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008935 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008936 if (!Compound->body_empty()) {
8937 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008938 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008939 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008940 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8941 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008942 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008943 }
John Wiegley429bb272011-04-08 18:41:53 +00008944 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008945 // Do function/array conversion on the last expression, but not
8946 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00008947 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8948 if (LastExpr.isInvalid())
8949 return ExprError();
8950 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00008951
John Wiegley429bb272011-04-08 18:41:53 +00008952 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
8953 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008954 InitializedEntity::InitializeResult(LPLoc,
8955 Ty,
8956 false),
8957 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00008958 LastExpr);
8959 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008960 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008961 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008962 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00008963 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008964 else
John Wiegley429bb272011-04-08 18:41:53 +00008965 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008966 StmtExprMayBindToTemp = true;
8967 }
8968 }
8969 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008970 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008971
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008972 // FIXME: Check that expression type is complete/non-abstract; statement
8973 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008974 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8975 if (StmtExprMayBindToTemp)
8976 return MaybeBindToTemporary(ResStmtExpr);
8977 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008978}
Steve Naroffd34e9152007-08-01 22:05:33 +00008979
John McCall60d7b3a2010-08-24 06:29:42 +00008980ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008981 TypeSourceInfo *TInfo,
8982 OffsetOfComponent *CompPtr,
8983 unsigned NumComponents,
8984 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008985 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008986 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008987 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008988
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008989 // We must have at least one component that refers to the type, and the first
8990 // one is known to be a field designator. Verify that the ArgTy represents
8991 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008992 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008993 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8994 << ArgTy << TypeRange);
8995
8996 // Type must be complete per C99 7.17p3 because a declaring a variable
8997 // with an incomplete type would be ill-formed.
8998 if (!Dependent
8999 && RequireCompleteType(BuiltinLoc, ArgTy,
9000 PDiag(diag::err_offsetof_incomplete_type)
9001 << TypeRange))
9002 return ExprError();
9003
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009004 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9005 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00009006 // FIXME: This diagnostic isn't actually visible because the location is in
9007 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009008 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00009009 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9010 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009011
9012 bool DidWarnAboutNonPOD = false;
9013 QualType CurrentType = ArgTy;
9014 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9015 llvm::SmallVector<OffsetOfNode, 4> Comps;
9016 llvm::SmallVector<Expr*, 4> Exprs;
9017 for (unsigned i = 0; i != NumComponents; ++i) {
9018 const OffsetOfComponent &OC = CompPtr[i];
9019 if (OC.isBrackets) {
9020 // Offset of an array sub-field. TODO: Should we allow vector elements?
9021 if (!CurrentType->isDependentType()) {
9022 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9023 if(!AT)
9024 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9025 << CurrentType);
9026 CurrentType = AT->getElementType();
9027 } else
9028 CurrentType = Context.DependentTy;
9029
9030 // The expression must be an integral expression.
9031 // FIXME: An integral constant expression?
9032 Expr *Idx = static_cast<Expr*>(OC.U.E);
9033 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9034 !Idx->getType()->isIntegerType())
9035 return ExprError(Diag(Idx->getLocStart(),
9036 diag::err_typecheck_subscript_not_integer)
9037 << Idx->getSourceRange());
9038
9039 // Record this array index.
9040 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9041 Exprs.push_back(Idx);
9042 continue;
9043 }
9044
9045 // Offset of a field.
9046 if (CurrentType->isDependentType()) {
9047 // We have the offset of a field, but we can't look into the dependent
9048 // type. Just record the identifier of the field.
9049 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9050 CurrentType = Context.DependentTy;
9051 continue;
9052 }
9053
9054 // We need to have a complete type to look into.
9055 if (RequireCompleteType(OC.LocStart, CurrentType,
9056 diag::err_offsetof_incomplete_type))
9057 return ExprError();
9058
9059 // Look for the designated field.
9060 const RecordType *RC = CurrentType->getAs<RecordType>();
9061 if (!RC)
9062 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9063 << CurrentType);
9064 RecordDecl *RD = RC->getDecl();
9065
9066 // C++ [lib.support.types]p5:
9067 // The macro offsetof accepts a restricted set of type arguments in this
9068 // International Standard. type shall be a POD structure or a POD union
9069 // (clause 9).
9070 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9071 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009072 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009073 PDiag(diag::warn_offsetof_non_pod_type)
9074 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9075 << CurrentType))
9076 DidWarnAboutNonPOD = true;
9077 }
9078
9079 // Look for the field.
9080 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9081 LookupQualifiedName(R, RD);
9082 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009083 IndirectFieldDecl *IndirectMemberDecl = 0;
9084 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009085 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009086 MemberDecl = IndirectMemberDecl->getAnonField();
9087 }
9088
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009089 if (!MemberDecl)
9090 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9091 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9092 OC.LocEnd));
9093
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009094 // C99 7.17p3:
9095 // (If the specified member is a bit-field, the behavior is undefined.)
9096 //
9097 // We diagnose this as an error.
9098 if (MemberDecl->getBitWidth()) {
9099 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9100 << MemberDecl->getDeclName()
9101 << SourceRange(BuiltinLoc, RParenLoc);
9102 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9103 return ExprError();
9104 }
Eli Friedman19410a72010-08-05 10:11:36 +00009105
9106 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009107 if (IndirectMemberDecl)
9108 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009109
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009110 // If the member was found in a base class, introduce OffsetOfNodes for
9111 // the base class indirections.
9112 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9113 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009114 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009115 CXXBasePath &Path = Paths.front();
9116 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9117 B != BEnd; ++B)
9118 Comps.push_back(OffsetOfNode(B->Base));
9119 }
Eli Friedman19410a72010-08-05 10:11:36 +00009120
Francois Pichet87c2e122010-11-21 06:08:52 +00009121 if (IndirectMemberDecl) {
9122 for (IndirectFieldDecl::chain_iterator FI =
9123 IndirectMemberDecl->chain_begin(),
9124 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9125 assert(isa<FieldDecl>(*FI));
9126 Comps.push_back(OffsetOfNode(OC.LocStart,
9127 cast<FieldDecl>(*FI), OC.LocEnd));
9128 }
9129 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009130 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009131
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009132 CurrentType = MemberDecl->getType().getNonReferenceType();
9133 }
9134
9135 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9136 TInfo, Comps.data(), Comps.size(),
9137 Exprs.data(), Exprs.size(), RParenLoc));
9138}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009139
John McCall60d7b3a2010-08-24 06:29:42 +00009140ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009141 SourceLocation BuiltinLoc,
9142 SourceLocation TypeLoc,
9143 ParsedType argty,
9144 OffsetOfComponent *CompPtr,
9145 unsigned NumComponents,
9146 SourceLocation RPLoc) {
9147
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009148 TypeSourceInfo *ArgTInfo;
9149 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
9150 if (ArgTy.isNull())
9151 return ExprError();
9152
Eli Friedman5a15dc12010-08-05 10:15:45 +00009153 if (!ArgTInfo)
9154 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9155
9156 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9157 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009158}
9159
9160
John McCall60d7b3a2010-08-24 06:29:42 +00009161ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009162 Expr *CondExpr,
9163 Expr *LHSExpr, Expr *RHSExpr,
9164 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009165 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9166
John McCallf89e55a2010-11-18 06:31:45 +00009167 ExprValueKind VK = VK_RValue;
9168 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009169 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009170 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009171 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009172 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009173 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009174 } else {
9175 // The conditional expression is required to be a constant expression.
9176 llvm::APSInt condEval(32);
9177 SourceLocation ExpLoc;
9178 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00009179 return ExprError(Diag(ExpLoc,
9180 diag::err_typecheck_choose_expr_requires_constant)
9181 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00009182
Sebastian Redl28507842009-02-26 14:39:58 +00009183 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009184 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9185
9186 resType = ActiveExpr->getType();
9187 ValueDependent = ActiveExpr->isValueDependent();
9188 VK = ActiveExpr->getValueKind();
9189 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009190 }
9191
Sebastian Redlf53597f2009-03-15 17:47:39 +00009192 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009193 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009194 resType->isDependentType(),
9195 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009196}
9197
Steve Naroff4eb206b2008-09-03 18:15:37 +00009198//===----------------------------------------------------------------------===//
9199// Clang Extensions.
9200//===----------------------------------------------------------------------===//
9201
9202/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00009203void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009204 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9205 PushBlockScope(BlockScope, Block);
9206 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009207 if (BlockScope)
9208 PushDeclContext(BlockScope, Block);
9209 else
9210 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00009211}
9212
Mike Stump98eb8a72009-02-04 22:31:32 +00009213void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009214 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009215 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009216 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009217
John McCallbf1a0282010-06-04 23:28:52 +00009218 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009219 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009220
John McCall711c52b2011-01-05 12:14:39 +00009221 // GetTypeForDeclarator always produces a function type for a block
9222 // literal signature. Furthermore, it is always a FunctionProtoType
9223 // unless the function was written with a typedef.
9224 assert(T->isFunctionType() &&
9225 "GetTypeForDeclarator made a non-function block signature");
9226
9227 // Look for an explicit signature in that function type.
9228 FunctionProtoTypeLoc ExplicitSignature;
9229
9230 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9231 if (isa<FunctionProtoTypeLoc>(tmp)) {
9232 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9233
9234 // Check whether that explicit signature was synthesized by
9235 // GetTypeForDeclarator. If so, don't save that as part of the
9236 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009237 if (ExplicitSignature.getLocalRangeBegin() ==
9238 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009239 // This would be much cheaper if we stored TypeLocs instead of
9240 // TypeSourceInfos.
9241 TypeLoc Result = ExplicitSignature.getResultLoc();
9242 unsigned Size = Result.getFullDataSize();
9243 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9244 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9245
9246 ExplicitSignature = FunctionProtoTypeLoc();
9247 }
John McCall82dc0092010-06-04 11:21:44 +00009248 }
Mike Stump1eb44332009-09-09 15:08:12 +00009249
John McCall711c52b2011-01-05 12:14:39 +00009250 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9251 CurBlock->FunctionType = T;
9252
9253 const FunctionType *Fn = T->getAs<FunctionType>();
9254 QualType RetTy = Fn->getResultType();
9255 bool isVariadic =
9256 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9257
John McCallc71a4912010-06-04 19:02:56 +00009258 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009259
John McCall82dc0092010-06-04 11:21:44 +00009260 // Don't allow returning a objc interface by value.
9261 if (RetTy->isObjCObjectType()) {
9262 Diag(ParamInfo.getSourceRange().getBegin(),
9263 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9264 return;
9265 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009266
John McCall82dc0092010-06-04 11:21:44 +00009267 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009268 // return type. TODO: what should we do with declarators like:
9269 // ^ * { ... }
9270 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00009271 if (RetTy != Context.DependentTy)
9272 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009273
John McCall82dc0092010-06-04 11:21:44 +00009274 // Push block parameters from the declarator if we had them.
John McCallc71a4912010-06-04 19:02:56 +00009275 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009276 if (ExplicitSignature) {
9277 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9278 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009279 if (Param->getIdentifier() == 0 &&
9280 !Param->isImplicit() &&
9281 !Param->isInvalidDecl() &&
9282 !getLangOptions().CPlusPlus)
9283 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009284 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009285 }
John McCall82dc0092010-06-04 11:21:44 +00009286
9287 // Fake up parameter variables if we have a typedef, like
9288 // ^ fntype { ... }
9289 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9290 for (FunctionProtoType::arg_type_iterator
9291 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9292 ParmVarDecl *Param =
9293 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9294 ParamInfo.getSourceRange().getBegin(),
9295 *I);
John McCallc71a4912010-06-04 19:02:56 +00009296 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009297 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009298 }
John McCall82dc0092010-06-04 11:21:44 +00009299
John McCallc71a4912010-06-04 19:02:56 +00009300 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009301 if (!Params.empty()) {
John McCallc71a4912010-06-04 19:02:56 +00009302 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregor82aa7132010-11-01 18:37:59 +00009303 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9304 CurBlock->TheDecl->param_end(),
9305 /*CheckParameterNames=*/false);
9306 }
9307
John McCall82dc0092010-06-04 11:21:44 +00009308 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009309 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009310
John McCallc71a4912010-06-04 19:02:56 +00009311 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00009312 Diag(ParamInfo.getAttributes()->getLoc(),
9313 diag::warn_attribute_sentinel_not_variadic) << 1;
9314 // FIXME: remove the attribute.
9315 }
9316
9317 // Put the parameter variables in scope. We can bail out immediately
9318 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009319 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009320 return;
9321
Steve Naroff090276f2008-10-10 01:28:17 +00009322 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009323 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9324 (*AI)->setOwningFunction(CurBlock->TheDecl);
9325
Steve Naroff090276f2008-10-10 01:28:17 +00009326 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009327 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009328 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009329
Steve Naroff090276f2008-10-10 01:28:17 +00009330 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009331 }
John McCall7a9813c2010-01-22 00:28:27 +00009332 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009333}
9334
9335/// ActOnBlockError - If there is an error parsing a block, this callback
9336/// is invoked to pop the information about the block from the action impl.
9337void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00009338 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009339 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009340 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009341}
9342
9343/// ActOnBlockStmtExpr - This is called when the body of a block statement
9344/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009345ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009346 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009347 // If blocks are disabled, emit an error.
9348 if (!LangOpts.Blocks)
9349 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009350
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009351 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009352
Steve Naroff090276f2008-10-10 01:28:17 +00009353 PopDeclContext();
9354
Steve Naroff4eb206b2008-09-03 18:15:37 +00009355 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009356 if (!BSI->ReturnType.isNull())
9357 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009358
Mike Stump56925862009-07-28 22:04:01 +00009359 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009360 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009361
John McCall469a1eb2011-02-02 13:00:07 +00009362 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00009363 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
9364 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00009365
John McCallc71a4912010-06-04 19:02:56 +00009366 // If the user wrote a function type in some form, try to use that.
9367 if (!BSI->FunctionType.isNull()) {
9368 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9369
9370 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9371 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9372
9373 // Turn protoless block types into nullary block types.
9374 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009375 FunctionProtoType::ExtProtoInfo EPI;
9376 EPI.ExtInfo = Ext;
9377 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009378
9379 // Otherwise, if we don't need to change anything about the function type,
9380 // preserve its sugar structure.
9381 } else if (FTy->getResultType() == RetTy &&
9382 (!NoReturn || FTy->getNoReturnAttr())) {
9383 BlockTy = BSI->FunctionType;
9384
9385 // Otherwise, make the minimal modifications to the function type.
9386 } else {
9387 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009388 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9389 EPI.TypeQuals = 0; // FIXME: silently?
9390 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009391 BlockTy = Context.getFunctionType(RetTy,
9392 FPT->arg_type_begin(),
9393 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009394 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009395 }
9396
9397 // If we don't have a function type, just build one from nothing.
9398 } else {
John McCalle23cf432010-12-14 08:05:40 +00009399 FunctionProtoType::ExtProtoInfo EPI;
Eli Friedmana49218e2011-04-09 08:18:08 +00009400 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, false, 0, CC_Default);
John McCalle23cf432010-12-14 08:05:40 +00009401 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009402 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009403
John McCallc71a4912010-06-04 19:02:56 +00009404 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9405 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009406 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009407
Chris Lattner17a78302009-04-19 05:28:12 +00009408 // If needed, diagnose invalid gotos and switches in the block.
John McCall781472f2010-08-25 08:40:02 +00009409 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00009410 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009411
Chris Lattnere476bdc2011-02-17 23:58:47 +00009412 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009413
John McCall469a1eb2011-02-02 13:00:07 +00009414 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCalle0054f62010-08-25 05:56:39 +00009415
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009416 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9417 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009418 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009419}
9420
John McCall60d7b3a2010-08-24 06:29:42 +00009421ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallb3d87482010-08-24 05:47:05 +00009422 Expr *expr, ParsedType type,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009423 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009424 TypeSourceInfo *TInfo;
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009425 GetTypeFromParser(type, &TInfo);
John McCall9ae2f072010-08-23 23:25:46 +00009426 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009427}
9428
John McCall60d7b3a2010-08-24 06:29:42 +00009429ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00009430 Expr *E, TypeSourceInfo *TInfo,
9431 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009432 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00009433
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009434 // Get the va_list type
9435 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009436 if (VaListType->isArrayType()) {
9437 // Deal with implicit array decay; for example, on x86-64,
9438 // va_list is an array, but it's supposed to decay to
9439 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009440 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00009441 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00009442 ExprResult Result = UsualUnaryConversions(E);
9443 if (Result.isInvalid())
9444 return ExprError();
9445 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009446 } else {
9447 // Otherwise, the va_list argument must be an l-value because
9448 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00009449 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00009450 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00009451 return ExprError();
9452 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009453
Douglas Gregordd027302009-05-19 23:10:31 +00009454 if (!E->isTypeDependent() &&
9455 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00009456 return ExprError(Diag(E->getLocStart(),
9457 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009458 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00009459 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009460
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009461 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009462 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009463
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009464 QualType T = TInfo->getType().getNonLValueExprType(Context);
9465 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009466}
9467
John McCall60d7b3a2010-08-24 06:29:42 +00009468ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009469 // The type of __null will be int or long, depending on the size of
9470 // pointers on the target.
9471 QualType Ty;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009472 unsigned pw = Context.Target.getPointerWidth(0);
9473 if (pw == Context.Target.getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009474 Ty = Context.IntTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009475 else if (pw == Context.Target.getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009476 Ty = Context.LongTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009477 else if (pw == Context.Target.getLongLongWidth())
9478 Ty = Context.LongLongTy;
9479 else {
9480 assert(!"I don't know size of pointer!");
9481 Ty = Context.IntTy;
9482 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009483
Sebastian Redlf53597f2009-03-15 17:47:39 +00009484 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009485}
9486
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009487static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009488 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009489 if (!SemaRef.getLangOptions().ObjC1)
9490 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009491
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009492 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9493 if (!PT)
9494 return;
9495
9496 // Check if the destination is of type 'id'.
9497 if (!PT->isObjCIdType()) {
9498 // Check if the destination is the 'NSString' interface.
9499 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9500 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9501 return;
9502 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009503
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009504 // Strip off any parens and casts.
9505 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9506 if (!SL || SL->isWide())
9507 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009508
Douglas Gregor849b2432010-03-31 17:46:05 +00009509 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009510}
9511
Chris Lattner5cf216b2008-01-04 18:04:52 +00009512bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9513 SourceLocation Loc,
9514 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009515 Expr *SrcExpr, AssignmentAction Action,
9516 bool *Complained) {
9517 if (Complained)
9518 *Complained = false;
9519
Chris Lattner5cf216b2008-01-04 18:04:52 +00009520 // Decode the result (notice that AST's are still created for extensions).
9521 bool isInvalid = false;
9522 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00009523 FixItHint Hint;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009524
Chris Lattner5cf216b2008-01-04 18:04:52 +00009525 switch (ConvTy) {
9526 default: assert(0 && "Unknown conversion type");
9527 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009528 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009529 DiagKind = diag::ext_typecheck_convert_pointer_int;
9530 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009531 case IntToPointer:
9532 DiagKind = diag::ext_typecheck_convert_int_pointer;
9533 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009534 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009535 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009536 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9537 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009538 case IncompatiblePointerSign:
9539 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9540 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009541 case FunctionVoidPointer:
9542 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9543 break;
John McCall86c05f32011-02-01 00:10:29 +00009544 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009545 // Perform array-to-pointer decay if necessary.
9546 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9547
John McCall86c05f32011-02-01 00:10:29 +00009548 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9549 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9550 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9551 DiagKind = diag::err_typecheck_incompatible_address_space;
9552 break;
9553 }
9554
9555 llvm_unreachable("unknown error case for discarding qualifiers!");
9556 // fallthrough
9557 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009558 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009559 // If the qualifiers lost were because we were applying the
9560 // (deprecated) C++ conversion from a string literal to a char*
9561 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9562 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009563 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009564 // bit of refactoring (so that the second argument is an
9565 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009566 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009567 // C++ semantics.
9568 if (getLangOptions().CPlusPlus &&
9569 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9570 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009571 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9572 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009573 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009574 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009575 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009576 case IntToBlockPointer:
9577 DiagKind = diag::err_int_to_block_pointer;
9578 break;
9579 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009580 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009581 break;
Steve Naroff39579072008-10-14 22:18:38 +00009582 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009583 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009584 // it can give a more specific diagnostic.
9585 DiagKind = diag::warn_incompatible_qualified_id;
9586 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009587 case IncompatibleVectors:
9588 DiagKind = diag::warn_incompatible_vectors;
9589 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009590 case Incompatible:
9591 DiagKind = diag::err_typecheck_convert_incompatible;
9592 isInvalid = true;
9593 break;
9594 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009595
Douglas Gregord4eea832010-04-09 00:35:39 +00009596 QualType FirstType, SecondType;
9597 switch (Action) {
9598 case AA_Assigning:
9599 case AA_Initializing:
9600 // The destination type comes first.
9601 FirstType = DstType;
9602 SecondType = SrcType;
9603 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009604
Douglas Gregord4eea832010-04-09 00:35:39 +00009605 case AA_Returning:
9606 case AA_Passing:
9607 case AA_Converting:
9608 case AA_Sending:
9609 case AA_Casting:
9610 // The source type comes first.
9611 FirstType = SrcType;
9612 SecondType = DstType;
9613 break;
9614 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009615
Douglas Gregord4eea832010-04-09 00:35:39 +00009616 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009617 << SrcExpr->getSourceRange() << Hint;
Douglas Gregora41a8c52010-04-22 00:20:18 +00009618 if (Complained)
9619 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009620 return isInvalid;
9621}
Anders Carlssone21555e2008-11-30 19:50:32 +00009622
Chris Lattner3bf68932009-04-25 21:59:05 +00009623bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009624 llvm::APSInt ICEResult;
9625 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9626 if (Result)
9627 *Result = ICEResult;
9628 return false;
9629 }
9630
Anders Carlssone21555e2008-11-30 19:50:32 +00009631 Expr::EvalResult EvalResult;
9632
Mike Stumpeed9cac2009-02-19 03:04:26 +00009633 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00009634 EvalResult.HasSideEffects) {
9635 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9636
9637 if (EvalResult.Diag) {
9638 // We only show the note if it's not the usual "invalid subexpression"
9639 // or if it's actually in a subexpression.
9640 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9641 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9642 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9643 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009644
Anders Carlssone21555e2008-11-30 19:50:32 +00009645 return true;
9646 }
9647
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009648 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9649 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00009650
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009651 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009652 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9653 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009654 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009655
Anders Carlssone21555e2008-11-30 19:50:32 +00009656 if (Result)
9657 *Result = EvalResult.Val.getInt();
9658 return false;
9659}
Douglas Gregore0762c92009-06-19 23:52:42 +00009660
Douglas Gregor2afce722009-11-26 00:44:06 +00009661void
Mike Stump1eb44332009-09-09 15:08:12 +00009662Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009663 ExprEvalContexts.push_back(
9664 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00009665}
9666
Mike Stump1eb44332009-09-09 15:08:12 +00009667void
Douglas Gregor2afce722009-11-26 00:44:06 +00009668Sema::PopExpressionEvaluationContext() {
9669 // Pop the current expression evaluation context off the stack.
9670 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9671 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009672
Douglas Gregor06d33692009-12-12 07:57:52 +00009673 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9674 if (Rec.PotentiallyReferenced) {
9675 // Mark any remaining declarations in the current position of the stack
9676 // as "referenced". If they were not meant to be referenced, semantic
9677 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009678 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00009679 I = Rec.PotentiallyReferenced->begin(),
9680 IEnd = Rec.PotentiallyReferenced->end();
9681 I != IEnd; ++I)
9682 MarkDeclarationReferenced(I->first, I->second);
9683 }
9684
9685 if (Rec.PotentiallyDiagnosed) {
9686 // Emit any pending diagnostics.
9687 for (PotentiallyEmittedDiagnostics::iterator
9688 I = Rec.PotentiallyDiagnosed->begin(),
9689 IEnd = Rec.PotentiallyDiagnosed->end();
9690 I != IEnd; ++I)
9691 Diag(I->first, I->second);
9692 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009693 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009694
9695 // When are coming out of an unevaluated context, clear out any
9696 // temporaries that we may have created as part of the evaluation of
9697 // the expression in that context: they aren't relevant because they
9698 // will never be constructed.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009699 if (Rec.Context == Unevaluated &&
Douglas Gregor2afce722009-11-26 00:44:06 +00009700 ExprTemporaries.size() > Rec.NumTemporaries)
9701 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9702 ExprTemporaries.end());
9703
9704 // Destroy the popped expression evaluation record.
9705 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009706}
Douglas Gregore0762c92009-06-19 23:52:42 +00009707
9708/// \brief Note that the given declaration was referenced in the source code.
9709///
9710/// This routine should be invoke whenever a given declaration is referenced
9711/// in the source code, and where that reference occurred. If this declaration
9712/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9713/// C99 6.9p3), then the declaration will be marked as used.
9714///
9715/// \param Loc the location where the declaration was referenced.
9716///
9717/// \param D the declaration that has been referenced by the source code.
9718void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9719 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009720
Douglas Gregorc070cc62010-06-17 23:14:26 +00009721 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009722 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009723
Douglas Gregorb5352cf2009-10-08 21:35:42 +00009724 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9725 // template or not. The reason for this is that unevaluated expressions
9726 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9727 // -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009728 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009729 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009730 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009731 return;
9732 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009733
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009734 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9735 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009736
Douglas Gregore0762c92009-06-19 23:52:42 +00009737 // Do not mark anything as "used" within a dependent context; wait for
9738 // an instantiation.
9739 if (CurContext->isDependentContext())
9740 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009741
Douglas Gregor2afce722009-11-26 00:44:06 +00009742 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009743 case Unevaluated:
9744 // We are in an expression that is not potentially evaluated; do nothing.
9745 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009746
Douglas Gregorac7610d2009-06-22 20:57:11 +00009747 case PotentiallyEvaluated:
9748 // We are in a potentially-evaluated expression, so this declaration is
9749 // "used"; handle this below.
9750 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009751
Douglas Gregorac7610d2009-06-22 20:57:11 +00009752 case PotentiallyPotentiallyEvaluated:
9753 // We are in an expression that may be potentially evaluated; queue this
9754 // declaration reference until we know whether the expression is
9755 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009756 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009757 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009758
9759 case PotentiallyEvaluatedIfUsed:
9760 // Referenced declarations will only be used if the construct in the
9761 // containing expression is used.
9762 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009763 }
Mike Stump1eb44332009-09-09 15:08:12 +00009764
Douglas Gregore0762c92009-06-19 23:52:42 +00009765 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009766 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009767 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00009768 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00009769 if (Constructor->getParent()->hasTrivialConstructor())
9770 return;
9771 if (!Constructor->isUsed(false))
9772 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00009773 } else if (Constructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00009774 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009775 if (!Constructor->isUsed(false))
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009776 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9777 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009778
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009779 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009780 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009781 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009782 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009783 if (Destructor->isVirtual())
9784 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009785 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9786 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9787 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009788 if (!MethodDecl->isUsed(false))
Douglas Gregor39957dc2010-05-01 15:04:51 +00009789 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009790 } else if (MethodDecl->isVirtual())
9791 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009792 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009793 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +00009794 // Recursive functions should be marked when used from another function.
9795 if (CurContext == Function) return;
9796
Mike Stump1eb44332009-09-09 15:08:12 +00009797 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009798 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009799 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009800 bool AlreadyInstantiated = false;
9801 if (FunctionTemplateSpecializationInfo *SpecInfo
9802 = Function->getTemplateSpecializationInfo()) {
9803 if (SpecInfo->getPointOfInstantiation().isInvalid())
9804 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009805 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009806 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009807 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009808 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009809 = Function->getMemberSpecializationInfo()) {
9810 if (MSInfo->getPointOfInstantiation().isInvalid())
9811 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009812 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009813 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009814 AlreadyInstantiated = true;
9815 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009816
Douglas Gregor60406be2010-01-16 22:29:39 +00009817 if (!AlreadyInstantiated) {
9818 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9819 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9820 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9821 Loc));
9822 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00009823 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00009824 }
John McCall15e310a2011-02-19 02:53:41 +00009825 } else {
9826 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +00009827 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9828 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00009829 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00009830 MarkDeclarationReferenced(Loc, *i);
9831 }
John McCall15e310a2011-02-19 02:53:41 +00009832 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009833
John McCall15e310a2011-02-19 02:53:41 +00009834 // Keep track of used but undefined functions.
9835 if (!Function->isPure() && !Function->hasBody() &&
9836 Function->getLinkage() != ExternalLinkage) {
9837 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9838 if (old.isInvalid()) old = Loc;
9839 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00009840
John McCall15e310a2011-02-19 02:53:41 +00009841 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +00009842 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009843 }
Mike Stump1eb44332009-09-09 15:08:12 +00009844
Douglas Gregore0762c92009-06-19 23:52:42 +00009845 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00009846 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00009847 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009848 Var->getInstantiatedFromStaticDataMember()) {
9849 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9850 assert(MSInfo && "Missing member specialization information?");
9851 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9852 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9853 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth62c78d52010-08-25 08:44:16 +00009854 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009855 }
9856 }
Mike Stump1eb44332009-09-09 15:08:12 +00009857
John McCall77efc682011-02-21 19:25:48 +00009858 // Keep track of used but undefined variables. We make a hole in
9859 // the warning for static const data members with in-line
9860 // initializers.
John McCall15e310a2011-02-19 02:53:41 +00009861 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall77efc682011-02-21 19:25:48 +00009862 && Var->getLinkage() != ExternalLinkage
9863 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall15e310a2011-02-19 02:53:41 +00009864 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9865 if (old.isInvalid()) old = Loc;
9866 }
Douglas Gregor7caa6822009-07-24 20:34:43 +00009867
Douglas Gregore0762c92009-06-19 23:52:42 +00009868 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00009869 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00009870 }
Douglas Gregore0762c92009-06-19 23:52:42 +00009871}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009872
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009873namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009874 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009875 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009876 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009877 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9878 Sema &S;
9879 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009880
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009881 public:
9882 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009883
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009884 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009885
9886 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9887 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009888 };
9889}
9890
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009891bool MarkReferencedDecls::TraverseTemplateArgument(
9892 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009893 if (Arg.getKind() == TemplateArgument::Declaration) {
9894 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9895 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009896
9897 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009898}
9899
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009900bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009901 if (ClassTemplateSpecializationDecl *Spec
9902 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9903 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +00009904 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009905 }
9906
Chandler Carruthe3e210c2010-06-10 10:31:57 +00009907 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009908}
9909
9910void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9911 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009912 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009913}
9914
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009915namespace {
9916 /// \brief Helper class that marks all of the declarations referenced by
9917 /// potentially-evaluated subexpressions as "referenced".
9918 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9919 Sema &S;
9920
9921 public:
9922 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9923
9924 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9925
9926 void VisitDeclRefExpr(DeclRefExpr *E) {
9927 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9928 }
9929
9930 void VisitMemberExpr(MemberExpr *E) {
9931 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009932 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009933 }
9934
9935 void VisitCXXNewExpr(CXXNewExpr *E) {
9936 if (E->getConstructor())
9937 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9938 if (E->getOperatorNew())
9939 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9940 if (E->getOperatorDelete())
9941 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009942 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009943 }
9944
9945 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9946 if (E->getOperatorDelete())
9947 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +00009948 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9949 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9950 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9951 S.MarkDeclarationReferenced(E->getLocStart(),
9952 S.LookupDestructor(Record));
9953 }
9954
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009955 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009956 }
9957
9958 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9959 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009960 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009961 }
9962
9963 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9964 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9965 }
Douglas Gregor102ff972010-10-19 17:17:35 +00009966
9967 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9968 Visit(E->getExpr());
9969 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009970 };
9971}
9972
9973/// \brief Mark any declarations that appear within this expression or any
9974/// potentially-evaluated subexpressions as "referenced".
9975void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9976 EvaluatedExprMarker(*this).Visit(E);
9977}
9978
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009979/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9980/// of the program being compiled.
9981///
9982/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009983/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009984/// possibility that the code will actually be executable. Code in sizeof()
9985/// expressions, code used only during overload resolution, etc., are not
9986/// potentially evaluated. This routine will suppress such diagnostics or,
9987/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009988/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009989/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009990///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009991/// This routine should be used for all diagnostics that describe the run-time
9992/// behavior of a program, such as passing a non-POD value through an ellipsis.
9993/// Failure to do so will likely result in spurious diagnostics or failures
9994/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek762696f2011-02-23 01:51:43 +00009995bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009996 const PartialDiagnostic &PD) {
9997 switch (ExprEvalContexts.back().Context ) {
9998 case Unevaluated:
9999 // The argument will never be evaluated, so don't complain.
10000 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010001
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010002 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010003 case PotentiallyEvaluatedIfUsed:
Ted Kremenek351ba912011-02-23 01:52:04 +000010004 if (stmt && getCurFunctionOrMethodDecl()) {
10005 FunctionScopes.back()->PossiblyUnreachableDiags.
10006 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
10007 }
10008 else
10009 Diag(Loc, PD);
10010
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010011 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010012
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010013 case PotentiallyPotentiallyEvaluated:
10014 ExprEvalContexts.back().addDiagnostic(Loc, PD);
10015 break;
10016 }
10017
10018 return false;
10019}
10020
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010021bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10022 CallExpr *CE, FunctionDecl *FD) {
10023 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10024 return false;
10025
10026 PartialDiagnostic Note =
10027 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
10028 << FD->getDeclName() : PDiag();
10029 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010030
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010031 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010032 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010033 PDiag(diag::err_call_function_incomplete_return)
10034 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010035 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010036 << CE->getSourceRange(),
10037 std::make_pair(NoteLoc, Note)))
10038 return true;
10039
10040 return false;
10041}
10042
Douglas Gregor92c3a042011-01-19 16:50:08 +000010043// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000010044// will prevent this condition from triggering, which is what we want.
10045void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10046 SourceLocation Loc;
10047
John McCalla52ef082009-11-11 02:41:58 +000010048 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000010049 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000010050
John McCall5a881bb2009-10-12 21:59:07 +000010051 if (isa<BinaryOperator>(E)) {
10052 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +000010053 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000010054 return;
10055
Douglas Gregor92c3a042011-01-19 16:50:08 +000010056 IsOrAssign = Op->getOpcode() == BO_OrAssign;
10057
John McCallc8d8ac52009-11-12 00:06:05 +000010058 // Greylist some idioms by putting them into a warning subcategory.
10059 if (ObjCMessageExpr *ME
10060 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10061 Selector Sel = ME->getSelector();
10062
John McCallc8d8ac52009-11-12 00:06:05 +000010063 // self = [<foo> init...]
Douglas Gregor813d8342011-02-18 22:29:55 +000010064 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000010065 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10066
10067 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000010068 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000010069 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10070 }
John McCalla52ef082009-11-11 02:41:58 +000010071
John McCall5a881bb2009-10-12 21:59:07 +000010072 Loc = Op->getOperatorLoc();
10073 } else if (isa<CXXOperatorCallExpr>(E)) {
10074 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +000010075 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000010076 return;
10077
Douglas Gregor92c3a042011-01-19 16:50:08 +000010078 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000010079 Loc = Op->getOperatorLoc();
10080 } else {
10081 // Not an assignment.
10082 return;
10083 }
10084
Douglas Gregor55b38842010-04-14 16:09:52 +000010085 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000010086
10087 if (IsOrAssign)
10088 Diag(Loc, diag::note_condition_or_assign_to_comparison)
10089 << FixItHint::CreateReplacement(Loc, "!=");
10090 else
10091 Diag(Loc, diag::note_condition_assign_to_comparison)
10092 << FixItHint::CreateReplacement(Loc, "==");
10093
Fariborz Jahanian81ab3cf2011-04-13 20:31:26 +000010094 SourceLocation Open = E->getSourceRange().getBegin();
10095 SourceLocation Close = E->getSourceRange().getEnd();
Fariborz Jahanian60274612011-04-13 22:18:37 +000010096 SourceLocation LocForEndOfToken =
10097 Close.isMacroID() ? Close : PP.getLocForEndOfToken(Close);
10098 Diag(Loc, diag::note_condition_assign_silence)
10099 << FixItHint::CreateInsertion(Open, "(")
10100 << FixItHint::CreateInsertion(LocForEndOfToken, ")");
John McCall5a881bb2009-10-12 21:59:07 +000010101}
10102
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010103/// \brief Redundant parentheses over an equality comparison can indicate
10104/// that the user intended an assignment used as condition.
10105void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000010106 // Don't warn if the parens came from a macro.
10107 SourceLocation parenLoc = parenE->getLocStart();
10108 if (parenLoc.isInvalid() || parenLoc.isMacroID())
10109 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000010110 // Don't warn for dependent expressions.
10111 if (parenE->isTypeDependent())
10112 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000010113
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010114 Expr *E = parenE->IgnoreParens();
10115
10116 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000010117 if (opE->getOpcode() == BO_EQ &&
10118 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10119 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010120 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000010121
Ted Kremenekf7275cd2011-02-02 02:20:30 +000010122 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
10123 Diag(Loc, diag::note_equality_comparison_to_assign)
10124 << FixItHint::CreateReplacement(Loc, "=");
10125 Diag(Loc, diag::note_equality_comparison_silence)
10126 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
10127 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010128 }
10129}
10130
John Wiegley429bb272011-04-08 18:41:53 +000010131ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000010132 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010133 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10134 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000010135
10136 if (!E->isTypeDependent()) {
John Wiegley429bb272011-04-08 18:41:53 +000010137 if (E->isBoundMemberFunction(Context)) {
10138 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000010139 << E->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +000010140 return ExprError();
10141 }
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000010142
John McCallf6a16482010-12-04 03:47:34 +000010143 if (getLangOptions().CPlusPlus)
10144 return CheckCXXBooleanCondition(E); // C++ 6.4p4
10145
John Wiegley429bb272011-04-08 18:41:53 +000010146 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10147 if (ERes.isInvalid())
10148 return ExprError();
10149 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000010150
10151 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000010152 if (!T->isScalarType()) { // C99 6.8.4.1p1
10153 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10154 << T << E->getSourceRange();
10155 return ExprError();
10156 }
John McCall5a881bb2009-10-12 21:59:07 +000010157 }
10158
John Wiegley429bb272011-04-08 18:41:53 +000010159 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000010160}
Douglas Gregor586596f2010-05-06 17:25:47 +000010161
John McCall60d7b3a2010-08-24 06:29:42 +000010162ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
10163 Expr *Sub) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +000010164 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +000010165 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010166
10167 return CheckBooleanCondition(Sub, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000010168}
John McCall2a984ca2010-10-12 00:20:44 +000010169
John McCall1de4d4e2011-04-07 08:22:57 +000010170namespace {
John McCall755d8492011-04-12 00:42:48 +000010171 /// A visitor for rebuilding a call to an __unknown_any expression
10172 /// to have an appropriate type.
10173 struct RebuildUnknownAnyFunction
10174 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10175
10176 Sema &S;
10177
10178 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10179
10180 ExprResult VisitStmt(Stmt *S) {
10181 llvm_unreachable("unexpected statement!");
10182 return ExprError();
10183 }
10184
10185 ExprResult VisitExpr(Expr *expr) {
10186 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
10187 << expr->getSourceRange();
10188 return ExprError();
10189 }
10190
10191 /// Rebuild an expression which simply semantically wraps another
10192 /// expression which it shares the type and value kind of.
10193 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10194 ExprResult subResult = Visit(expr->getSubExpr());
10195 if (subResult.isInvalid()) return ExprError();
10196
10197 Expr *subExpr = subResult.take();
10198 expr->setSubExpr(subExpr);
10199 expr->setType(subExpr->getType());
10200 expr->setValueKind(subExpr->getValueKind());
10201 assert(expr->getObjectKind() == OK_Ordinary);
10202 return expr;
10203 }
10204
10205 ExprResult VisitParenExpr(ParenExpr *paren) {
10206 return rebuildSugarExpr(paren);
10207 }
10208
10209 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10210 return rebuildSugarExpr(op);
10211 }
10212
10213 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10214 ExprResult subResult = Visit(op->getSubExpr());
10215 if (subResult.isInvalid()) return ExprError();
10216
10217 Expr *subExpr = subResult.take();
10218 op->setSubExpr(subExpr);
10219 op->setType(S.Context.getPointerType(subExpr->getType()));
10220 assert(op->getValueKind() == VK_RValue);
10221 assert(op->getObjectKind() == OK_Ordinary);
10222 return op;
10223 }
10224
10225 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
10226 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
10227
10228 expr->setType(decl->getType());
10229
10230 assert(expr->getValueKind() == VK_RValue);
10231 if (S.getLangOptions().CPlusPlus &&
10232 !(isa<CXXMethodDecl>(decl) &&
10233 cast<CXXMethodDecl>(decl)->isInstance()))
10234 expr->setValueKind(VK_LValue);
10235
10236 return expr;
10237 }
10238
10239 ExprResult VisitMemberExpr(MemberExpr *mem) {
10240 return resolveDecl(mem, mem->getMemberDecl());
10241 }
10242
10243 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
10244 return resolveDecl(ref, ref->getDecl());
10245 }
10246 };
10247}
10248
10249/// Given a function expression of unknown-any type, try to rebuild it
10250/// to have a function type.
10251static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
10252 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
10253 if (result.isInvalid()) return ExprError();
10254 return S.DefaultFunctionArrayConversion(result.take());
10255}
10256
10257namespace {
John McCall379b5152011-04-11 07:02:50 +000010258 /// A visitor for rebuilding an expression of type __unknown_anytype
10259 /// into one which resolves the type directly on the referring
10260 /// expression. Strict preservation of the original source
10261 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000010262 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000010263 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000010264
10265 Sema &S;
10266
10267 /// The current destination type.
10268 QualType DestType;
10269
10270 RebuildUnknownAnyExpr(Sema &S, QualType castType)
10271 : S(S), DestType(castType) {}
10272
John McCalla5fc4722011-04-09 22:50:59 +000010273 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000010274 llvm_unreachable("unexpected statement!");
John McCalla5fc4722011-04-09 22:50:59 +000010275 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010276 }
10277
John McCall379b5152011-04-11 07:02:50 +000010278 ExprResult VisitExpr(Expr *expr) {
10279 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10280 << expr->getSourceRange();
10281 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010282 }
10283
John McCall379b5152011-04-11 07:02:50 +000010284 ExprResult VisitCallExpr(CallExpr *call);
10285 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
10286
John McCalla5fc4722011-04-09 22:50:59 +000010287 /// Rebuild an expression which simply semantically wraps another
10288 /// expression which it shares the type and value kind of.
10289 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10290 ExprResult subResult = Visit(expr->getSubExpr());
John McCall755d8492011-04-12 00:42:48 +000010291 if (subResult.isInvalid()) return ExprError();
John McCalla5fc4722011-04-09 22:50:59 +000010292 Expr *subExpr = subResult.take();
10293 expr->setSubExpr(subExpr);
10294 expr->setType(subExpr->getType());
10295 expr->setValueKind(subExpr->getValueKind());
10296 assert(expr->getObjectKind() == OK_Ordinary);
10297 return expr;
10298 }
John McCall1de4d4e2011-04-07 08:22:57 +000010299
John McCalla5fc4722011-04-09 22:50:59 +000010300 ExprResult VisitParenExpr(ParenExpr *paren) {
10301 return rebuildSugarExpr(paren);
10302 }
10303
10304 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10305 return rebuildSugarExpr(op);
10306 }
10307
John McCall755d8492011-04-12 00:42:48 +000010308 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10309 const PointerType *ptr = DestType->getAs<PointerType>();
10310 if (!ptr) {
10311 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
10312 << op->getSourceRange();
10313 return ExprError();
10314 }
10315 assert(op->getValueKind() == VK_RValue);
10316 assert(op->getObjectKind() == OK_Ordinary);
10317 op->setType(DestType);
10318
10319 // Build the sub-expression as if it were an object of the pointee type.
10320 DestType = ptr->getPointeeType();
10321 ExprResult subResult = Visit(op->getSubExpr());
10322 if (subResult.isInvalid()) return ExprError();
10323 op->setSubExpr(subResult.take());
10324 return op;
10325 }
10326
John McCall379b5152011-04-11 07:02:50 +000010327 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCalla5fc4722011-04-09 22:50:59 +000010328
John McCall755d8492011-04-12 00:42:48 +000010329 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCalla5fc4722011-04-09 22:50:59 +000010330
John McCall755d8492011-04-12 00:42:48 +000010331 ExprResult VisitMemberExpr(MemberExpr *mem) {
10332 return resolveDecl(mem, mem->getMemberDecl());
10333 }
John McCalla5fc4722011-04-09 22:50:59 +000010334
10335 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall379b5152011-04-11 07:02:50 +000010336 return resolveDecl(ref, ref->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000010337 }
10338 };
10339}
10340
John McCall379b5152011-04-11 07:02:50 +000010341/// Rebuilds a call expression which yielded __unknown_anytype.
10342ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
10343 Expr *callee = call->getCallee();
10344
10345 enum FnKind {
10346 FK_Function,
10347 FK_FunctionPointer,
10348 FK_BlockPointer
10349 };
10350
10351 FnKind kind;
10352 QualType type = callee->getType();
10353 if (type->isFunctionType()) {
10354 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
10355 kind = FK_Function;
10356 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
10357 type = ptr->getPointeeType();
10358 kind = FK_FunctionPointer;
10359 } else {
10360 type = type->castAs<BlockPointerType>()->getPointeeType();
10361 kind = FK_BlockPointer;
10362 }
10363 const FunctionType *fnType = type->castAs<FunctionType>();
10364
10365 // Verify that this is a legal result type of a function.
10366 if (DestType->isArrayType() || DestType->isFunctionType()) {
10367 unsigned diagID = diag::err_func_returning_array_function;
10368 if (kind == FK_BlockPointer)
10369 diagID = diag::err_block_returning_array_function;
10370
10371 S.Diag(call->getExprLoc(), diagID)
10372 << DestType->isFunctionType() << DestType;
10373 return ExprError();
10374 }
10375
10376 // Otherwise, go ahead and set DestType as the call's result.
10377 call->setType(DestType.getNonLValueExprType(S.Context));
10378 call->setValueKind(Expr::getValueKindForType(DestType));
10379 assert(call->getObjectKind() == OK_Ordinary);
10380
10381 // Rebuild the function type, replacing the result type with DestType.
10382 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
10383 DestType = S.Context.getFunctionType(DestType,
10384 proto->arg_type_begin(),
10385 proto->getNumArgs(),
10386 proto->getExtProtoInfo());
10387 else
10388 DestType = S.Context.getFunctionNoProtoType(DestType,
10389 fnType->getExtInfo());
10390
10391 // Rebuild the appropriate pointer-to-function type.
10392 switch (kind) {
10393 case FK_Function:
10394 // Nothing to do.
10395 break;
10396
10397 case FK_FunctionPointer:
10398 DestType = S.Context.getPointerType(DestType);
10399 break;
10400
10401 case FK_BlockPointer:
10402 DestType = S.Context.getBlockPointerType(DestType);
10403 break;
10404 }
10405
10406 // Finally, we can recurse.
10407 ExprResult calleeResult = Visit(callee);
10408 if (!calleeResult.isUsable()) return ExprError();
10409 call->setCallee(calleeResult.take());
10410
10411 // Bind a temporary if necessary.
10412 return S.MaybeBindToTemporary(call);
10413}
10414
10415ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall755d8492011-04-12 00:42:48 +000010416 ObjCMethodDecl *method = msg->getMethodDecl();
10417 assert(method && "__unknown_anytype message without result type?");
John McCall379b5152011-04-11 07:02:50 +000010418
John McCall755d8492011-04-12 00:42:48 +000010419 // Verify that this is a legal result type of a call.
10420 if (DestType->isArrayType() || DestType->isFunctionType()) {
10421 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
10422 << DestType->isFunctionType() << DestType;
10423 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010424 }
10425
John McCall755d8492011-04-12 00:42:48 +000010426 assert(method->getResultType() == S.Context.UnknownAnyTy);
10427 method->setResultType(DestType);
10428
John McCall379b5152011-04-11 07:02:50 +000010429 // Change the type of the message.
John McCall755d8492011-04-12 00:42:48 +000010430 msg->setType(DestType.getNonReferenceType());
10431 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000010432
John McCall755d8492011-04-12 00:42:48 +000010433 return S.MaybeBindToTemporary(msg);
John McCall379b5152011-04-11 07:02:50 +000010434}
10435
10436ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall755d8492011-04-12 00:42:48 +000010437 // The only case we should ever see here is a function-to-pointer decay.
John McCall379b5152011-04-11 07:02:50 +000010438 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall379b5152011-04-11 07:02:50 +000010439 assert(ice->getValueKind() == VK_RValue);
10440 assert(ice->getObjectKind() == OK_Ordinary);
10441
John McCall755d8492011-04-12 00:42:48 +000010442 ice->setType(DestType);
10443
John McCall379b5152011-04-11 07:02:50 +000010444 // Rebuild the sub-expression as the pointee (function) type.
10445 DestType = DestType->castAs<PointerType>()->getPointeeType();
10446
10447 ExprResult result = Visit(ice->getSubExpr());
10448 if (!result.isUsable()) return ExprError();
10449
10450 ice->setSubExpr(result.take());
10451 return S.Owned(ice);
10452}
10453
John McCall755d8492011-04-12 00:42:48 +000010454ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall379b5152011-04-11 07:02:50 +000010455 ExprValueKind valueKind = VK_LValue;
John McCall379b5152011-04-11 07:02:50 +000010456 QualType type = DestType;
10457
10458 // We know how to make this work for certain kinds of decls:
10459
10460 // - functions
John McCall755d8492011-04-12 00:42:48 +000010461 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
10462 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
John McCall379b5152011-04-11 07:02:50 +000010463 if (method->isInstance()) valueKind = VK_RValue;
10464
10465 // This is true because FunctionDecls must always have function
10466 // type, so we can't be resolving the entire thing at once.
10467 assert(type->isFunctionType());
10468
10469 // Function references aren't l-values in C.
10470 if (!S.getLangOptions().CPlusPlus)
10471 valueKind = VK_RValue;
10472
10473 // - variables
10474 } else if (isa<VarDecl>(decl)) {
John McCall755d8492011-04-12 00:42:48 +000010475 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
10476 type = refTy->getPointeeType();
John McCall379b5152011-04-11 07:02:50 +000010477 } else if (type->isFunctionType()) {
John McCall755d8492011-04-12 00:42:48 +000010478 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
10479 << decl << expr->getSourceRange();
10480 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010481 }
10482
10483 // - nothing else
10484 } else {
10485 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10486 << decl << expr->getSourceRange();
10487 return ExprError();
10488 }
10489
John McCall755d8492011-04-12 00:42:48 +000010490 decl->setType(DestType);
10491 expr->setType(type);
10492 expr->setValueKind(valueKind);
10493 return S.Owned(expr);
John McCall379b5152011-04-11 07:02:50 +000010494}
10495
John McCall1de4d4e2011-04-07 08:22:57 +000010496/// Check a cast of an unknown-any type. We intentionally only
10497/// trigger this for C-style casts.
John Wiegley429bb272011-04-08 18:41:53 +000010498ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
10499 Expr *castExpr, CastKind &castKind,
10500 ExprValueKind &VK, CXXCastPath &path) {
John McCall1de4d4e2011-04-07 08:22:57 +000010501 // Rewrite the casted expression from scratch.
John McCalla5fc4722011-04-09 22:50:59 +000010502 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
10503 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010504
John McCalla5fc4722011-04-09 22:50:59 +000010505 castExpr = result.take();
10506 VK = castExpr->getValueKind();
10507 castKind = CK_NoOp;
10508
10509 return castExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000010510}
10511
10512static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
10513 Expr *orig = e;
John McCall379b5152011-04-11 07:02:50 +000010514 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000010515 while (true) {
10516 e = e->IgnoreParenImpCasts();
John McCall379b5152011-04-11 07:02:50 +000010517 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall1de4d4e2011-04-07 08:22:57 +000010518 e = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000010519 diagID = diag::err_uncasted_call_of_unknown_any;
10520 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000010521 break;
John McCall379b5152011-04-11 07:02:50 +000010522 }
John McCall1de4d4e2011-04-07 08:22:57 +000010523 }
10524
John McCall379b5152011-04-11 07:02:50 +000010525 SourceLocation loc;
10526 NamedDecl *d;
10527 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10528 loc = ref->getLocation();
10529 d = ref->getDecl();
10530 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
10531 loc = mem->getMemberLoc();
10532 d = mem->getMemberDecl();
10533 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
10534 diagID = diag::err_uncasted_call_of_unknown_any;
10535 loc = msg->getSelectorLoc();
10536 d = msg->getMethodDecl();
10537 assert(d && "unknown method returning __unknown_any?");
10538 } else {
10539 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10540 << e->getSourceRange();
10541 return ExprError();
10542 }
10543
10544 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000010545
10546 // Never recoverable.
10547 return ExprError();
10548}
10549
John McCall2a984ca2010-10-12 00:20:44 +000010550/// Check for operands with placeholder types and complain if found.
10551/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000010552ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall1de4d4e2011-04-07 08:22:57 +000010553 // Placeholder types are always *exactly* the appropriate builtin type.
10554 QualType type = E->getType();
John McCall2a984ca2010-10-12 00:20:44 +000010555
John McCall1de4d4e2011-04-07 08:22:57 +000010556 // Overloaded expressions.
10557 if (type == Context.OverloadTy)
10558 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregordb2eae62011-03-16 19:16:25 +000010559 E->getSourceRange(),
John McCall1de4d4e2011-04-07 08:22:57 +000010560 QualType(),
10561 diag::err_ovl_unresolvable);
10562
10563 // Expressions of unknown type.
10564 if (type == Context.UnknownAnyTy)
10565 return diagnoseUnknownAnyExpr(*this, E);
10566
10567 assert(!type->isPlaceholderType());
10568 return Owned(E);
John McCall2a984ca2010-10-12 00:20:44 +000010569}