blob: 16b6f447215b9889df9b313340beb934b32be37f [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"
Sebastian Redlf79a7192011-04-29 08:19:30 +000019#include "clang/AST/ASTMutationListener.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000020#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000022#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000023#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000024#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000025#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000027#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000028#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000032#include "clang/Lex/LiteralSupport.h"
33#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000034#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Designator.h"
36#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000037#include "clang/Sema/ScopeInfo.h"
John McCall19510852010-08-20 18:27:03 +000038#include "clang/Sema/ParsedTemplate.h"
Anna Zaks67221552011-07-28 19:51:27 +000039#include "clang/Sema/SemaFixItUtils.h"
John McCall7cd088e2010-08-24 07:21:54 +000040#include "clang/Sema/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000041using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000042using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000043
David Chisnall0f436562009-08-17 16:35:33 +000044
Douglas Gregor48f3bb92009-02-18 21:56:37 +000045/// \brief Determine whether the use of this declaration is valid, and
46/// emit any corresponding diagnostics.
47///
48/// This routine diagnoses various problems with referencing
49/// declarations that can occur when using a declaration. For example,
50/// it might warn if a deprecated or unavailable declaration is being
51/// used, or produce an error (and return true) if a C++0x deleted
52/// function is being used.
53///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000054/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattner52338262009-10-25 22:31:57 +000055/// decls.
56///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000057/// \returns true if there was an error (this declaration cannot be
58/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000059///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000060bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +000061 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor9b623632010-10-12 23:32:35 +000062 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
63 // If there were any diagnostics suppressed by template argument deduction,
64 // emit them now.
Chris Lattner5f9e2722011-07-23 10:55:15 +000065 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +000066 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
67 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000068 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor9b623632010-10-12 23:32:35 +000069 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
70 Diag(Suppressed[I].first, Suppressed[I].second);
71
72 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000073 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +000074 // entry from the table, because we want to avoid ever emitting these
75 // diagnostics again.
76 Suppressed.clear();
77 }
78 }
79
Richard Smith34b41d92011-02-20 03:19:35 +000080 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +000081 if (ParsingInitForAutoVars.count(D)) {
82 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
83 << D->getDeclName();
84 return true;
Richard Smith34b41d92011-02-20 03:19:35 +000085 }
86
Douglas Gregor48f3bb92009-02-18 21:56:37 +000087 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000088 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000089 if (FD->isDeleted()) {
90 Diag(Loc, diag::err_deleted_function_use);
John McCallf85e1932011-06-15 23:02:42 +000091 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000092 return true;
93 }
Douglas Gregor25d944a2009-02-24 04:26:15 +000094 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000095
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000096 // See if this declaration is unavailable or deprecated.
97 std::string Message;
98 switch (D->getAvailability(&Message)) {
99 case AR_Available:
100 case AR_NotYetIntroduced:
101 break;
102
103 case AR_Deprecated:
104 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
105 break;
106
107 case AR_Unavailable:
Argyrios Kyrtzidis12189f52011-06-17 17:28:30 +0000108 if (cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) {
109 if (Message.empty()) {
110 if (!UnknownObjCClass)
111 Diag(Loc, diag::err_unavailable) << D->getDeclName();
112 else
113 Diag(Loc, diag::warn_unavailable_fwdclass_message)
114 << D->getDeclName();
115 }
116 else
117 Diag(Loc, diag::err_unavailable_message)
118 << D->getDeclName() << Message;
119 Diag(D->getLocation(), diag::note_unavailable_here)
120 << isa<FunctionDecl>(D) << false;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000121 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000122 break;
123 }
124
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000125 // Warn if this is used but marked unused.
126 if (D->hasAttr<UnusedAttr>())
127 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
128
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000129 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000130}
131
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000132/// \brief Retrieve the message suffix that should be added to a
133/// diagnostic complaining about the given function being deleted or
134/// unavailable.
135std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
136 // FIXME: C++0x implicitly-deleted special member functions could be
137 // detected here so that we could improve diagnostics to say, e.g.,
138 // "base class 'A' had a deleted copy constructor".
139 if (FD->isDeleted())
140 return std::string();
141
142 std::string Message;
143 if (FD->getAvailability(&Message))
144 return ": " + Message;
145
146 return std::string();
147}
148
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000149/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +0000150/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000151/// attribute. It warns if call does not have the sentinel argument.
152///
153void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000154 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000155 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000156 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000157 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000158
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000159 int sentinelPos = attr->getSentinel();
160 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +0000161
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000162 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000163 bool warnNotEnoughArgs = false;
164 int isMethod = 0;
165 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
166 // skip over named parameters.
167 ObjCMethodDecl::param_iterator P, E = MD->param_end();
168 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
169 if (nullPos)
170 --nullPos;
171 else
172 ++i;
173 }
174 warnNotEnoughArgs = (P != E || i >= NumArgs);
175 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000176 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000177 // skip over named parameters.
178 ObjCMethodDecl::param_iterator P, E = FD->param_end();
179 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
180 if (nullPos)
181 --nullPos;
182 else
183 ++i;
184 }
185 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000186 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000187 // block or function pointer call.
188 QualType Ty = V->getType();
189 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000190 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000191 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
192 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000193 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
194 unsigned NumArgsInProto = Proto->getNumArgs();
195 unsigned k;
196 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
197 if (nullPos)
198 --nullPos;
199 else
200 ++i;
201 }
202 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
203 }
204 if (Ty->isBlockPointerType())
205 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000206 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000207 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000208 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000209 return;
210
211 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000212 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000213 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000214 return;
215 }
216 int sentinel = i;
217 while (sentinelPos > 0 && i < NumArgs-1) {
218 --sentinelPos;
219 ++i;
220 }
221 if (sentinelPos > 0) {
222 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000223 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000224 return;
225 }
226 while (i < NumArgs-1) {
227 ++i;
228 ++sentinel;
229 }
230 Expr *sentinelExpr = Args[sentinel];
John McCall8eb662e2010-05-06 23:53:00 +0000231 if (!sentinelExpr) return;
232 if (sentinelExpr->isTypeDependent()) return;
233 if (sentinelExpr->isValueDependent()) return;
Anders Carlsson343e6ff2010-11-05 15:21:33 +0000234
235 // nullptr_t is always treated as null.
236 if (sentinelExpr->getType()->isNullPtrType()) return;
237
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000238 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-05-06 23:53:00 +0000239 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
240 Expr::NPC_ValueDependentIsNull))
241 return;
242
243 // Unfortunately, __null has type 'int'.
244 if (isa<GNUNullExpr>(sentinelExpr)) return;
245
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000246 SourceLocation MissingNilLoc
247 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
248 std::string NullValue;
249 if (isMethod && PP.getIdentifierInfo("nil")->hasMacroDefinition())
250 NullValue = "nil";
251 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
252 NullValue = "NULL";
253 else if (Context.getTypeSize(Context.IntTy)
254 == Context.getTypeSize(Context.getSizeType()))
255 NullValue = "0";
256 else
257 NullValue = "0L";
258
259 Diag(MissingNilLoc, diag::warn_missing_sentinel)
260 << isMethod
261 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall8eb662e2010-05-06 23:53:00 +0000262 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000263}
264
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000265SourceRange Sema::getExprRange(ExprTy *E) const {
266 Expr *Ex = (Expr *)E;
267 return Ex? Ex->getSourceRange() : SourceRange();
268}
269
Chris Lattnere7a2e912008-07-25 21:10:04 +0000270//===----------------------------------------------------------------------===//
271// Standard Promotions and Conversions
272//===----------------------------------------------------------------------===//
273
Chris Lattnere7a2e912008-07-25 21:10:04 +0000274/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000275ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000276 QualType Ty = E->getType();
277 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
278
Chris Lattnere7a2e912008-07-25 21:10:04 +0000279 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000280 E = ImpCastExprToType(E, Context.getPointerType(Ty),
281 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000282 else if (Ty->isArrayType()) {
283 // In C90 mode, arrays only promote to pointers if the array expression is
284 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
285 // type 'array of type' is converted to an expression that has type 'pointer
286 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
287 // that has type 'array of type' ...". The relevant change is "an lvalue"
288 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000289 //
290 // C++ 4.2p1:
291 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
292 // T" can be converted to an rvalue of type "pointer to T".
293 //
John McCall7eb0a9e2010-11-24 05:12:34 +0000294 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000295 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
296 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000297 }
John Wiegley429bb272011-04-08 18:41:53 +0000298 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000299}
300
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000301static void CheckForNullPointerDereference(Sema &S, Expr *E) {
302 // Check to see if we are dereferencing a null pointer. If so,
303 // and if not volatile-qualified, this is undefined behavior that the
304 // optimizer will delete, so warn about it. People sometimes try to use this
305 // to get a deterministic trap and are surprised by clang's behavior. This
306 // only handles the pattern "*null", which is a very syntactic check.
307 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
308 if (UO->getOpcode() == UO_Deref &&
309 UO->getSubExpr()->IgnoreParenCasts()->
310 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
311 !UO->getType().isVolatileQualified()) {
312 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
313 S.PDiag(diag::warn_indirection_through_null)
314 << UO->getSubExpr()->getSourceRange());
315 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
316 S.PDiag(diag::note_indirection_through_null));
317 }
318}
319
John Wiegley429bb272011-04-08 18:41:53 +0000320ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000321 // C++ [conv.lval]p1:
322 // A glvalue of a non-function, non-array type T can be
323 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000324 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000325
John McCall409fa9a2010-12-06 20:48:59 +0000326 QualType T = E->getType();
327 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000328
John McCall409fa9a2010-12-06 20:48:59 +0000329 // Create a load out of an ObjCProperty l-value, if necessary.
330 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +0000331 ExprResult Res = ConvertPropertyForRValue(E);
332 if (Res.isInvalid())
333 return Owned(E);
334 E = Res.take();
John McCall409fa9a2010-12-06 20:48:59 +0000335 if (!E->isGLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000336 return Owned(E);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000337 }
John McCall409fa9a2010-12-06 20:48:59 +0000338
339 // We don't want to throw lvalue-to-rvalue casts on top of
340 // expressions of certain types in C++.
341 if (getLangOptions().CPlusPlus &&
342 (E->getType() == Context.OverloadTy ||
343 T->isDependentType() ||
344 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000345 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000346
347 // The C standard is actually really unclear on this point, and
348 // DR106 tells us what the result should be but not why. It's
349 // generally best to say that void types just doesn't undergo
350 // lvalue-to-rvalue at all. Note that expressions of unqualified
351 // 'void' type are never l-values, but qualified void can be.
352 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000353 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000354
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000355 CheckForNullPointerDereference(*this, E);
356
John McCall409fa9a2010-12-06 20:48:59 +0000357 // C++ [conv.lval]p1:
358 // [...] If T is a non-class type, the type of the prvalue is the
359 // cv-unqualified version of T. Otherwise, the type of the
360 // rvalue is T.
361 //
362 // C99 6.3.2.1p2:
363 // If the lvalue has qualified type, the value has the unqualified
364 // version of the type of the lvalue; otherwise, the value has the
365 // type of the lvalue.
366 if (T.hasQualifiers())
367 T = T.getUnqualifiedType();
Ted Kremeneka0125d82011-02-16 01:57:07 +0000368
John Wiegley429bb272011-04-08 18:41:53 +0000369 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
370 E, 0, VK_RValue));
John McCall409fa9a2010-12-06 20:48:59 +0000371}
372
John Wiegley429bb272011-04-08 18:41:53 +0000373ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
374 ExprResult Res = DefaultFunctionArrayConversion(E);
375 if (Res.isInvalid())
376 return ExprError();
377 Res = DefaultLvalueConversion(Res.take());
378 if (Res.isInvalid())
379 return ExprError();
380 return move(Res);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000381}
382
383
Chris Lattnere7a2e912008-07-25 21:10:04 +0000384/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000385/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000386/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000387/// apply if the array is an argument to the sizeof or address (&) operators.
388/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000389ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000390 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000391 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
392 if (Res.isInvalid())
393 return Owned(E);
394 E = Res.take();
John McCall0ae287a2010-12-01 04:43:34 +0000395
396 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000397 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCall0ae287a2010-12-01 04:43:34 +0000398
399 // Try to perform integral promotions if the object has a theoretically
400 // promotable type.
401 if (Ty->isIntegralOrUnscopedEnumerationType()) {
402 // C99 6.3.1.1p2:
403 //
404 // The following may be used in an expression wherever an int or
405 // unsigned int may be used:
406 // - an object or expression with an integer type whose integer
407 // conversion rank is less than or equal to the rank of int
408 // and unsigned int.
409 // - A bit-field of type _Bool, int, signed int, or unsigned int.
410 //
411 // If an int can represent all values of the original type, the
412 // value is converted to an int; otherwise, it is converted to an
413 // unsigned int. These are called the integer promotions. All
414 // other types are unchanged by the integer promotions.
415
416 QualType PTy = Context.isPromotableBitField(E);
417 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000418 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
419 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000420 }
421 if (Ty->isPromotableIntegerType()) {
422 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000423 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
424 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000425 }
Eli Friedman04e83572009-08-20 04:21:42 +0000426 }
John Wiegley429bb272011-04-08 18:41:53 +0000427 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000428}
429
Chris Lattner05faf172008-07-25 22:25:12 +0000430/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000431/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000432/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000433ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
434 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000435 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000436
John Wiegley429bb272011-04-08 18:41:53 +0000437 ExprResult Res = UsualUnaryConversions(E);
438 if (Res.isInvalid())
439 return Owned(E);
440 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000441
Chris Lattner05faf172008-07-25 22:25:12 +0000442 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000443 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000444 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
445
John McCall96a914a2011-08-27 22:06:17 +0000446 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-08-29 23:55:37 +0000447 // promotion, even on class types, but note:
448 // C++11 [conv.lval]p2:
449 // When an lvalue-to-rvalue conversion occurs in an unevaluated
450 // operand or a subexpression thereof the value contained in the
451 // referenced object is not accessed. Otherwise, if the glvalue
452 // has a class type, the conversion copy-initializes a temporary
453 // of type T from the glvalue and the result of the conversion
454 // is a prvalue for the temporary.
455 // FIXME: add some way to gate this entire thing for correctness in
456 // potentially potentially evaluated contexts.
John McCall96a914a2011-08-27 22:06:17 +0000457 if (getLangOptions().CPlusPlus && E->isGLValue() &&
458 ExprEvalContexts.back().Context != Unevaluated) {
John McCall5f8d6042011-08-27 01:09:30 +0000459 ExprResult Temp = PerformCopyInitialization(
460 InitializedEntity::InitializeTemporary(E->getType()),
461 E->getExprLoc(),
462 Owned(E));
463 if (Temp.isInvalid())
464 return ExprError();
465 E = Temp.get();
466 }
467
John Wiegley429bb272011-04-08 18:41:53 +0000468 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000469}
470
Chris Lattner312531a2009-04-12 08:11:20 +0000471/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
472/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley429bb272011-04-08 18:41:53 +0000473/// interfaces passed by value.
474ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000475 FunctionDecl *FDecl) {
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000476 ExprResult ExprRes = CheckPlaceholderExpr(E);
477 if (ExprRes.isInvalid())
478 return ExprError();
479
480 ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000481 if (ExprRes.isInvalid())
482 return ExprError();
483 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000485 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley429bb272011-04-08 18:41:53 +0000486 if (E->getType()->isObjCObjectType() &&
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000487 DiagRuntimeBehavior(E->getLocStart(), 0,
488 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
489 << E->getType() << CT))
John Wiegley429bb272011-04-08 18:41:53 +0000490 return ExprError();
John McCall5f8d6042011-08-27 01:09:30 +0000491
John McCallf85e1932011-06-15 23:02:42 +0000492 if (!E->getType().isPODType(Context)) {
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000493 // C++0x [expr.call]p7:
494 // Passing a potentially-evaluated argument of class type (Clause 9)
495 // having a non-trivial copy constructor, a non-trivial move constructor,
496 // or a non-trivial destructor, with no corresponding parameter,
497 // is conditionally-supported with implementation-defined semantics.
498 bool TrivialEnough = false;
499 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
500 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
501 if (Record->hasTrivialCopyConstructor() &&
502 Record->hasTrivialMoveConstructor() &&
503 Record->hasTrivialDestructor())
504 TrivialEnough = true;
505 }
506 }
John McCallf85e1932011-06-15 23:02:42 +0000507
508 if (!TrivialEnough &&
509 getLangOptions().ObjCAutoRefCount &&
510 E->getType()->isObjCLifetimeType())
511 TrivialEnough = true;
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000512
513 if (TrivialEnough) {
514 // Nothing to diagnose. This is okay.
515 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000516 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000517 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000518 << CT)) {
519 // Turn this into a trap.
520 CXXScopeSpec SS;
521 UnqualifiedId Name;
522 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
523 E->getLocStart());
524 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
525 if (TrapFn.isInvalid())
526 return ExprError();
527
528 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
529 MultiExprArg(), E->getLocEnd());
530 if (Call.isInvalid())
531 return ExprError();
532
533 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
534 Call.get(), E);
535 if (Comma.isInvalid())
John McCall66c20302011-08-26 18:41:18 +0000536 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000537 E = Comma.get();
538 }
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000539 }
540
John Wiegley429bb272011-04-08 18:41:53 +0000541 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000542}
543
Richard Trieu8289f492011-09-02 20:58:51 +0000544/// \brief Converts an integer to complex float type. Helper function of
545/// UsualArithmeticConversions()
546///
547/// \return false if the integer expression is an integer type and is
548/// successfully converted to the complex type.
549static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &intExpr,
550 ExprResult &complexExpr,
551 QualType intTy,
552 QualType complexTy,
553 bool skipCast) {
554 if (intTy->isComplexType() || intTy->isRealFloatingType()) return true;
555 if (skipCast) return false;
556 if (intTy->isIntegerType()) {
557 QualType fpTy = cast<ComplexType>(complexTy)->getElementType();
558 intExpr = S.ImpCastExprToType(intExpr.take(), fpTy, CK_IntegralToFloating);
559 intExpr = S.ImpCastExprToType(intExpr.take(), complexTy,
560 CK_FloatingRealToComplex);
561 } else {
562 assert(intTy->isComplexIntegerType());
563 intExpr = S.ImpCastExprToType(intExpr.take(), complexTy,
564 CK_IntegralComplexToFloatingComplex);
565 }
566 return false;
567}
568
569/// \brief Takes two complex float types and converts them to the same type.
570/// Helper function of UsualArithmeticConversions()
571static QualType
Richard Trieucafd30b2011-09-06 18:25:09 +0000572handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
573 ExprResult &RHS, QualType LHSType,
574 QualType RHSType,
575 bool isCompAssign) {
576 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000577
578 if (order < 0) {
579 // _Complex float -> _Complex double
580 if (!isCompAssign)
Richard Trieucafd30b2011-09-06 18:25:09 +0000581 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
582 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000583 }
584 if (order > 0)
585 // _Complex float -> _Complex double
Richard Trieucafd30b2011-09-06 18:25:09 +0000586 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
587 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000588}
589
590/// \brief Converts otherExpr to complex float and promotes complexExpr if
591/// necessary. Helper function of UsualArithmeticConversions()
592static QualType handleOtherComplexFloatConversion(Sema &S,
593 ExprResult &complexExpr,
594 ExprResult &otherExpr,
595 QualType complexTy,
596 QualType otherTy,
597 bool convertComplexExpr,
598 bool convertOtherExpr) {
599 int order = S.Context.getFloatingTypeOrder(complexTy, otherTy);
600
601 // If just the complexExpr is complex, the otherExpr needs to be converted,
602 // and the complexExpr might need to be promoted.
603 if (order > 0) { // complexExpr is wider
604 // float -> _Complex double
605 if (convertOtherExpr) {
606 QualType fp = cast<ComplexType>(complexTy)->getElementType();
607 otherExpr = S.ImpCastExprToType(otherExpr.take(), fp, CK_FloatingCast);
608 otherExpr = S.ImpCastExprToType(otherExpr.take(), complexTy,
609 CK_FloatingRealToComplex);
610 }
611 return complexTy;
612 }
613
614 // otherTy is at least as wide. Find its corresponding complex type.
615 QualType result = (order == 0 ? complexTy :
616 S.Context.getComplexType(otherTy));
617
618 // double -> _Complex double
619 if (convertOtherExpr)
620 otherExpr = S.ImpCastExprToType(otherExpr.take(), result,
621 CK_FloatingRealToComplex);
622
623 // _Complex float -> _Complex double
624 if (convertComplexExpr && order < 0)
625 complexExpr = S.ImpCastExprToType(complexExpr.take(), result,
626 CK_FloatingComplexCast);
627
628 return result;
629}
630
631/// \brief Handle arithmetic conversion with complex types. Helper function of
632/// UsualArithmeticConversions()
Richard Trieucafd30b2011-09-06 18:25:09 +0000633static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
634 ExprResult &RHS, QualType LHSType,
635 QualType RHSType,
636 bool isCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000637 // if we have an integer operand, the result is the complex type.
Richard Trieucafd30b2011-09-06 18:25:09 +0000638 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000639 /*skipCast*/false))
Richard Trieucafd30b2011-09-06 18:25:09 +0000640 return LHSType;
641 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000642 /*skipCast*/isCompAssign))
Richard Trieucafd30b2011-09-06 18:25:09 +0000643 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000644
645 // This handles complex/complex, complex/float, or float/complex.
646 // When both operands are complex, the shorter operand is converted to the
647 // type of the longer, and that is the type of the result. This corresponds
648 // to what is done when combining two real floating-point operands.
649 // The fun begins when size promotion occur across type domains.
650 // From H&S 6.3.4: When one operand is complex and the other is a real
651 // floating-point type, the less precise type is converted, within it's
652 // real or complex domain, to the precision of the other type. For example,
653 // when combining a "long double" with a "double _Complex", the
654 // "double _Complex" is promoted to "long double _Complex".
655
Richard Trieucafd30b2011-09-06 18:25:09 +0000656 bool LHSComplexFloat = LHSType->isComplexType();
657 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu8289f492011-09-02 20:58:51 +0000658
659 // If both are complex, just cast to the more precise type.
660 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieucafd30b2011-09-06 18:25:09 +0000661 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
662 LHSType, RHSType,
663 isCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000664
665 // If only one operand is complex, promote it if necessary and convert the
666 // other operand to complex.
667 if (LHSComplexFloat)
668 return handleOtherComplexFloatConversion(
Richard Trieucafd30b2011-09-06 18:25:09 +0000669 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!isCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000670 /*convertOtherExpr*/ true);
671
672 assert(RHSComplexFloat);
673 return handleOtherComplexFloatConversion(
Richard Trieucafd30b2011-09-06 18:25:09 +0000674 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieu8289f492011-09-02 20:58:51 +0000675 /*convertOtherExpr*/ !isCompAssign);
676}
677
678/// \brief Hande arithmetic conversion from integer to float. Helper function
679/// of UsualArithmeticConversions()
680static QualType handleIntToFloatConversion(Sema &S, ExprResult &floatExpr,
681 ExprResult &intExpr,
682 QualType floatTy, QualType intTy,
683 bool convertFloat, bool convertInt) {
684 if (intTy->isIntegerType()) {
685 if (convertInt)
686 // Convert intExpr to the lhs floating point type.
687 intExpr = S.ImpCastExprToType(intExpr.take(), floatTy,
688 CK_IntegralToFloating);
689 return floatTy;
690 }
691
692 // Convert both sides to the appropriate complex float.
693 assert(intTy->isComplexIntegerType());
694 QualType result = S.Context.getComplexType(floatTy);
695
696 // _Complex int -> _Complex float
697 if (convertInt)
698 intExpr = S.ImpCastExprToType(intExpr.take(), result,
699 CK_IntegralComplexToFloatingComplex);
700
701 // float -> _Complex float
702 if (convertFloat)
703 floatExpr = S.ImpCastExprToType(floatExpr.take(), result,
704 CK_FloatingRealToComplex);
705
706 return result;
707}
708
709/// \brief Handle arithmethic conversion with floating point types. Helper
710/// function of UsualArithmeticConversions()
711static QualType handleFloatConversion(Sema &S, ExprResult &lhsExpr,
712 ExprResult &rhsExpr, QualType lhs,
713 QualType rhs, bool isCompAssign) {
714 bool LHSFloat = lhs->isRealFloatingType();
715 bool RHSFloat = rhs->isRealFloatingType();
716
717 // If we have two real floating types, convert the smaller operand
718 // to the bigger result.
719 if (LHSFloat && RHSFloat) {
720 int order = S.Context.getFloatingTypeOrder(lhs, rhs);
721 if (order > 0) {
722 rhsExpr = S.ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
723 return lhs;
724 }
725
726 assert(order < 0 && "illegal float comparison");
727 if (!isCompAssign)
728 lhsExpr = S.ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
729 return rhs;
730 }
731
732 if (LHSFloat)
733 return handleIntToFloatConversion(S, lhsExpr, rhsExpr, lhs, rhs,
734 /*convertFloat=*/!isCompAssign,
735 /*convertInt=*/ true);
736 assert(RHSFloat);
737 return handleIntToFloatConversion(S, rhsExpr, lhsExpr, rhs, lhs,
738 /*convertInt=*/ true,
739 /*convertFloat=*/!isCompAssign);
740}
741
742/// \brief Handle conversions with GCC complex int extension. Helper function
743/// of UsualArithmeticConverions()
744// FIXME: if the operands are (int, _Complex long), we currently
745// don't promote the complex. Also, signedness?
746static QualType handleComplexIntConvsersion(Sema &S, ExprResult &lhsExpr,
747 ExprResult &rhsExpr, QualType lhs,
748 QualType rhs, bool isCompAssign) {
749 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
750 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
751
752 if (lhsComplexInt && rhsComplexInt) {
753 int order = S.Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
754 rhsComplexInt->getElementType());
755 assert(order && "inequal types with equal element ordering");
756 if (order > 0) {
757 // _Complex int -> _Complex long
758 rhsExpr = S.ImpCastExprToType(rhsExpr.take(), lhs,
759 CK_IntegralComplexCast);
760 return lhs;
761 }
762
763 if (!isCompAssign)
764 lhsExpr = S.ImpCastExprToType(lhsExpr.take(), rhs,
765 CK_IntegralComplexCast);
766 return rhs;
767 }
768
769 if (lhsComplexInt) {
770 // int -> _Complex int
771 rhsExpr = S.ImpCastExprToType(rhsExpr.take(), lhs,
772 CK_IntegralRealToComplex);
773 return lhs;
774 }
775
776 assert(rhsComplexInt);
777 // int -> _Complex int
778 if (!isCompAssign)
779 lhsExpr = S.ImpCastExprToType(lhsExpr.take(), rhs,
780 CK_IntegralRealToComplex);
781 return rhs;
782}
783
784/// \brief Handle integer arithmetic conversions. Helper function of
785/// UsualArithmeticConversions()
786static QualType handleIntegerConversion(Sema &S, ExprResult &lhsExpr,
787 ExprResult &rhsExpr, QualType lhs,
788 QualType rhs, bool isCompAssign) {
789 // The rules for this case are in C99 6.3.1.8
790 int order = S.Context.getIntegerTypeOrder(lhs, rhs);
791 bool lhsSigned = lhs->hasSignedIntegerRepresentation();
792 bool rhsSigned = rhs->hasSignedIntegerRepresentation();
793 if (lhsSigned == rhsSigned) {
794 // Same signedness; use the higher-ranked type
795 if (order >= 0) {
796 rhsExpr = S.ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
797 return lhs;
798 } else if (!isCompAssign)
799 lhsExpr = S.ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
800 return rhs;
801 } else if (order != (lhsSigned ? 1 : -1)) {
802 // The unsigned type has greater than or equal rank to the
803 // signed type, so use the unsigned type
804 if (rhsSigned) {
805 rhsExpr = S.ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
806 return lhs;
807 } else if (!isCompAssign)
808 lhsExpr = S.ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
809 return rhs;
810 } else if (S.Context.getIntWidth(lhs) != S.Context.getIntWidth(rhs)) {
811 // The two types are different widths; if we are here, that
812 // means the signed type is larger than the unsigned type, so
813 // use the signed type.
814 if (lhsSigned) {
815 rhsExpr = S.ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
816 return lhs;
817 } else if (!isCompAssign)
818 lhsExpr = S.ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
819 return rhs;
820 } else {
821 // The signed type is higher-ranked than the unsigned type,
822 // but isn't actually any bigger (like unsigned int and long
823 // on most 32-bit systems). Use the unsigned type corresponding
824 // to the signed type.
825 QualType result =
826 S.Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
827 rhsExpr = S.ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
828 if (!isCompAssign)
829 lhsExpr = S.ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
830 return result;
831 }
832}
833
Chris Lattnere7a2e912008-07-25 21:10:04 +0000834/// UsualArithmeticConversions - Performs various conversions that are common to
835/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000836/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000837/// responsible for emitting appropriate error diagnostics.
838/// FIXME: verify the conversion rules for "complex int" are consistent with
839/// GCC.
Richard Trieu67e29332011-08-02 04:35:43 +0000840QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr,
841 ExprResult &rhsExpr,
Chris Lattnere7a2e912008-07-25 21:10:04 +0000842 bool isCompAssign) {
John Wiegley429bb272011-04-08 18:41:53 +0000843 if (!isCompAssign) {
844 lhsExpr = UsualUnaryConversions(lhsExpr.take());
845 if (lhsExpr.isInvalid())
846 return QualType();
847 }
Eli Friedmanab3a8522009-03-28 01:22:36 +0000848
John Wiegley429bb272011-04-08 18:41:53 +0000849 rhsExpr = UsualUnaryConversions(rhsExpr.take());
850 if (rhsExpr.isInvalid())
851 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000852
Mike Stump1eb44332009-09-09 15:08:12 +0000853 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000854 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000855 QualType lhs =
John Wiegley429bb272011-04-08 18:41:53 +0000856 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000857 QualType rhs =
John Wiegley429bb272011-04-08 18:41:53 +0000858 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000859
860 // If both types are identical, no conversion is needed.
861 if (lhs == rhs)
862 return lhs;
863
864 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
865 // The caller can deal with this (e.g. pointer + int).
866 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
867 return lhs;
868
John McCallcf33b242010-11-13 08:17:45 +0000869 // Apply unary and bitfield promotions to the LHS's type.
870 QualType lhs_unpromoted = lhs;
871 if (lhs->isPromotableIntegerType())
872 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley429bb272011-04-08 18:41:53 +0000873 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +0000874 if (!LHSBitfieldPromoteTy.isNull())
875 lhs = LHSBitfieldPromoteTy;
John McCallcf33b242010-11-13 08:17:45 +0000876 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000877 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000878
John McCallcf33b242010-11-13 08:17:45 +0000879 // If both types are identical, no conversion is needed.
880 if (lhs == rhs)
881 return lhs;
882
883 // At this point, we have two different arithmetic types.
884
885 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu8289f492011-09-02 20:58:51 +0000886 if (lhs->isComplexType() || rhs->isComplexType())
887 return handleComplexFloatConversion(*this, lhsExpr, rhsExpr, lhs, rhs,
888 isCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000889
890 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu8289f492011-09-02 20:58:51 +0000891 if (lhs->isRealFloatingType() || rhs->isRealFloatingType())
892 return handleFloatConversion(*this, lhsExpr, rhsExpr, lhs, rhs,
893 isCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000894
895 // Handle GCC complex int extension.
Richard Trieu8289f492011-09-02 20:58:51 +0000896 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType())
897 return handleComplexIntConvsersion(*this, lhsExpr, rhsExpr, lhs, rhs,
898 isCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000899
900 // Finally, we have two differing integer types.
Richard Trieu8289f492011-09-02 20:58:51 +0000901 return handleIntegerConversion(*this, lhsExpr, rhsExpr, lhs, rhs,
902 isCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000903}
904
Chris Lattnere7a2e912008-07-25 21:10:04 +0000905//===----------------------------------------------------------------------===//
906// Semantic Analysis for various Expression Types
907//===----------------------------------------------------------------------===//
908
909
Peter Collingbournef111d932011-04-15 00:35:48 +0000910ExprResult
911Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
912 SourceLocation DefaultLoc,
913 SourceLocation RParenLoc,
914 Expr *ControllingExpr,
915 MultiTypeArg types,
916 MultiExprArg exprs) {
917 unsigned NumAssocs = types.size();
918 assert(NumAssocs == exprs.size());
919
920 ParsedType *ParsedTypes = types.release();
921 Expr **Exprs = exprs.release();
922
923 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
924 for (unsigned i = 0; i < NumAssocs; ++i) {
925 if (ParsedTypes[i])
926 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
927 else
928 Types[i] = 0;
929 }
930
931 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
932 ControllingExpr, Types, Exprs,
933 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +0000934 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +0000935 return ER;
936}
937
938ExprResult
939Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
940 SourceLocation DefaultLoc,
941 SourceLocation RParenLoc,
942 Expr *ControllingExpr,
943 TypeSourceInfo **Types,
944 Expr **Exprs,
945 unsigned NumAssocs) {
946 bool TypeErrorFound = false,
947 IsResultDependent = ControllingExpr->isTypeDependent(),
948 ContainsUnexpandedParameterPack
949 = ControllingExpr->containsUnexpandedParameterPack();
950
951 for (unsigned i = 0; i < NumAssocs; ++i) {
952 if (Exprs[i]->containsUnexpandedParameterPack())
953 ContainsUnexpandedParameterPack = true;
954
955 if (Types[i]) {
956 if (Types[i]->getType()->containsUnexpandedParameterPack())
957 ContainsUnexpandedParameterPack = true;
958
959 if (Types[i]->getType()->isDependentType()) {
960 IsResultDependent = true;
961 } else {
962 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
963 // complete object type other than a variably modified type."
964 unsigned D = 0;
965 if (Types[i]->getType()->isIncompleteType())
966 D = diag::err_assoc_type_incomplete;
967 else if (!Types[i]->getType()->isObjectType())
968 D = diag::err_assoc_type_nonobject;
969 else if (Types[i]->getType()->isVariablyModifiedType())
970 D = diag::err_assoc_type_variably_modified;
971
972 if (D != 0) {
973 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
974 << Types[i]->getTypeLoc().getSourceRange()
975 << Types[i]->getType();
976 TypeErrorFound = true;
977 }
978
979 // C1X 6.5.1.1p2 "No two generic associations in the same generic
980 // selection shall specify compatible types."
981 for (unsigned j = i+1; j < NumAssocs; ++j)
982 if (Types[j] && !Types[j]->getType()->isDependentType() &&
983 Context.typesAreCompatible(Types[i]->getType(),
984 Types[j]->getType())) {
985 Diag(Types[j]->getTypeLoc().getBeginLoc(),
986 diag::err_assoc_compatible_types)
987 << Types[j]->getTypeLoc().getSourceRange()
988 << Types[j]->getType()
989 << Types[i]->getType();
990 Diag(Types[i]->getTypeLoc().getBeginLoc(),
991 diag::note_compat_assoc)
992 << Types[i]->getTypeLoc().getSourceRange()
993 << Types[i]->getType();
994 TypeErrorFound = true;
995 }
996 }
997 }
998 }
999 if (TypeErrorFound)
1000 return ExprError();
1001
1002 // If we determined that the generic selection is result-dependent, don't
1003 // try to compute the result expression.
1004 if (IsResultDependent)
1005 return Owned(new (Context) GenericSelectionExpr(
1006 Context, KeyLoc, ControllingExpr,
1007 Types, Exprs, NumAssocs, DefaultLoc,
1008 RParenLoc, ContainsUnexpandedParameterPack));
1009
Chris Lattner5f9e2722011-07-23 10:55:15 +00001010 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +00001011 unsigned DefaultIndex = -1U;
1012 for (unsigned i = 0; i < NumAssocs; ++i) {
1013 if (!Types[i])
1014 DefaultIndex = i;
1015 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1016 Types[i]->getType()))
1017 CompatIndices.push_back(i);
1018 }
1019
1020 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
1021 // type compatible with at most one of the types named in its generic
1022 // association list."
1023 if (CompatIndices.size() > 1) {
1024 // We strip parens here because the controlling expression is typically
1025 // parenthesized in macro definitions.
1026 ControllingExpr = ControllingExpr->IgnoreParens();
1027 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1028 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1029 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001030 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001031 E = CompatIndices.end(); I != E; ++I) {
1032 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1033 diag::note_compat_assoc)
1034 << Types[*I]->getTypeLoc().getSourceRange()
1035 << Types[*I]->getType();
1036 }
1037 return ExprError();
1038 }
1039
1040 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
1041 // its controlling expression shall have type compatible with exactly one of
1042 // the types named in its generic association list."
1043 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1044 // We strip parens here because the controlling expression is typically
1045 // parenthesized in macro definitions.
1046 ControllingExpr = ControllingExpr->IgnoreParens();
1047 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1048 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1049 return ExprError();
1050 }
1051
1052 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1053 // type name that is compatible with the type of the controlling expression,
1054 // then the result expression of the generic selection is the expression
1055 // in that generic association. Otherwise, the result expression of the
1056 // generic selection is the expression in the default generic association."
1057 unsigned ResultIndex =
1058 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1059
1060 return Owned(new (Context) GenericSelectionExpr(
1061 Context, KeyLoc, ControllingExpr,
1062 Types, Exprs, NumAssocs, DefaultLoc,
1063 RParenLoc, ContainsUnexpandedParameterPack,
1064 ResultIndex));
1065}
1066
Steve Narofff69936d2007-09-16 03:34:24 +00001067/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001068/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1069/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1070/// multiple tokens. However, the common case is that StringToks points to one
1071/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001072///
John McCall60d7b3a2010-08-24 06:29:42 +00001073ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +00001074Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001075 assert(NumStringToks && "Must have at least one string!");
1076
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001077 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001078 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001079 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001080
Chris Lattner5f9e2722011-07-23 10:55:15 +00001081 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001082 for (unsigned i = 0; i != NumStringToks; ++i)
1083 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001084
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001085 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001086 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001087 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001088 else if (Literal.isUTF16())
1089 StrTy = Context.Char16Ty;
1090 else if (Literal.isUTF32())
1091 StrTy = Context.Char32Ty;
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001092 else if (Literal.Pascal)
1093 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001094
Douglas Gregor5cee1192011-07-27 05:40:30 +00001095 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1096 if (Literal.isWide())
1097 Kind = StringLiteral::Wide;
1098 else if (Literal.isUTF8())
1099 Kind = StringLiteral::UTF8;
1100 else if (Literal.isUTF16())
1101 Kind = StringLiteral::UTF16;
1102 else if (Literal.isUTF32())
1103 Kind = StringLiteral::UTF32;
1104
Douglas Gregor77a52232008-09-12 00:47:35 +00001105 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +00001106 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001107 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001108
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001109 // Get an array type for the string, according to C99 6.4.5. This includes
1110 // the nul terminator character as well as the string length for pascal
1111 // strings.
1112 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001113 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001114 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Reid Spencer5f016e22007-07-11 17:01:13 +00001116 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +00001117 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001118 Kind, Literal.Pascal, StrTy,
Sean Hunt6cf75022010-08-30 17:47:05 +00001119 &StringTokLocs[0],
1120 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001121}
1122
John McCall469a1eb2011-02-02 13:00:07 +00001123enum CaptureResult {
1124 /// No capture is required.
1125 CR_NoCapture,
1126
1127 /// A capture is required.
1128 CR_Capture,
1129
John McCall6b5a61b2011-02-07 10:33:21 +00001130 /// A by-ref capture is required.
1131 CR_CaptureByRef,
1132
John McCall469a1eb2011-02-02 13:00:07 +00001133 /// An error occurred when trying to capture the given variable.
1134 CR_Error
1135};
1136
1137/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +00001138///
John McCall469a1eb2011-02-02 13:00:07 +00001139/// \param var - the variable referenced
1140/// \param DC - the context which we couldn't capture through
1141static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +00001142diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001143 VarDecl *var, DeclContext *DC) {
1144 switch (S.ExprEvalContexts.back().Context) {
1145 case Sema::Unevaluated:
1146 // The argument will never be evaluated, so don't complain.
1147 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +00001148
John McCall469a1eb2011-02-02 13:00:07 +00001149 case Sema::PotentiallyEvaluated:
1150 case Sema::PotentiallyEvaluatedIfUsed:
1151 break;
Chris Lattner639e2d32008-10-20 05:16:36 +00001152
John McCall469a1eb2011-02-02 13:00:07 +00001153 case Sema::PotentiallyPotentiallyEvaluated:
1154 // FIXME: delay these!
1155 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +00001156 }
Mike Stump1eb44332009-09-09 15:08:12 +00001157
John McCall469a1eb2011-02-02 13:00:07 +00001158 // Don't diagnose about capture if we're not actually in code right
1159 // now; in general, there are more appropriate places that will
1160 // diagnose this.
1161 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1162
John McCall4f38f412011-03-22 23:15:50 +00001163 // Certain madnesses can happen with parameter declarations, which
1164 // we want to ignore.
1165 if (isa<ParmVarDecl>(var)) {
1166 // - If the parameter still belongs to the translation unit, then
1167 // we're actually just using one parameter in the declaration of
1168 // the next. This is useful in e.g. VLAs.
1169 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1170 return CR_NoCapture;
1171
1172 // - This particular madness can happen in ill-formed default
1173 // arguments; claim it's okay and let downstream code handle it.
1174 if (S.CurContext == var->getDeclContext()->getParent())
1175 return CR_NoCapture;
1176 }
John McCall469a1eb2011-02-02 13:00:07 +00001177
1178 DeclarationName functionName;
1179 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1180 functionName = fn->getDeclName();
1181 // FIXME: variable from enclosing block that we couldn't capture from!
1182
1183 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1184 << var->getIdentifier() << functionName;
1185 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1186 << var->getIdentifier();
1187
1188 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001189}
1190
John McCall6b5a61b2011-02-07 10:33:21 +00001191/// There is a well-formed capture at a particular scope level;
1192/// propagate it through all the nested blocks.
1193static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1194 const BlockDecl::Capture &capture) {
1195 VarDecl *var = capture.getVariable();
1196
1197 // Update all the inner blocks with the capture information.
1198 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1199 i != e; ++i) {
1200 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1201 innerBlock->Captures.push_back(
1202 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1203 /*nested*/ true, capture.getCopyExpr()));
1204 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1205 }
1206
1207 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1208}
1209
1210/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +00001211/// given value in the current context requires a variable capture.
1212///
1213/// This also keeps the captures set in the BlockScopeInfo records
1214/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +00001215static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001216 ValueDecl *value) {
1217 // Only variables ever require capture.
1218 VarDecl *var = dyn_cast<VarDecl>(value);
John McCall76a40212011-02-09 01:13:10 +00001219 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +00001220
1221 // Fast path: variables from the current context never require capture.
1222 DeclContext *DC = S.CurContext;
1223 if (var->getDeclContext() == DC) return CR_NoCapture;
1224
1225 // Only variables with local storage require capture.
1226 // FIXME: What about 'const' variables in C++?
1227 if (!var->hasLocalStorage()) return CR_NoCapture;
1228
1229 // Otherwise, we need to capture.
1230
1231 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +00001232 do {
1233 // Only blocks (and eventually C++0x closures) can capture; other
1234 // scopes don't work.
1235 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +00001236 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +00001237
1238 BlockScopeInfo *blockScope =
1239 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1240 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1241
John McCall6b5a61b2011-02-07 10:33:21 +00001242 // Check whether we've already captured it in this block. If so,
1243 // we're done.
1244 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1245 return propagateCapture(S, functionScopesIndex,
1246 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +00001247
1248 functionScopesIndex--;
1249 DC = cast<BlockDecl>(DC)->getDeclContext();
1250 } while (var->getDeclContext() != DC);
1251
John McCall6b5a61b2011-02-07 10:33:21 +00001252 // Okay, we descended all the way to the block that defines the variable.
1253 // Actually try to capture it.
1254 QualType type = var->getType();
1255
1256 // Prohibit variably-modified types.
1257 if (type->isVariablyModifiedType()) {
1258 S.Diag(loc, diag::err_ref_vm_type);
1259 S.Diag(var->getLocation(), diag::note_declared_at);
1260 return CR_Error;
1261 }
1262
1263 // Prohibit arrays, even in __block variables, but not references to
1264 // them.
1265 if (type->isArrayType()) {
1266 S.Diag(loc, diag::err_ref_array_type);
1267 S.Diag(var->getLocation(), diag::note_declared_at);
1268 return CR_Error;
1269 }
1270
1271 S.MarkDeclarationReferenced(loc, var);
1272
1273 // The BlocksAttr indicates the variable is bound by-reference.
1274 bool byRef = var->hasAttr<BlocksAttr>();
1275
1276 // Build a copy expression.
1277 Expr *copyExpr = 0;
John McCall642a75f2011-04-28 02:15:35 +00001278 const RecordType *rtype;
1279 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1280 (rtype = type->getAs<RecordType>())) {
1281
1282 // The capture logic needs the destructor, so make sure we mark it.
1283 // Usually this is unnecessary because most local variables have
1284 // their destructors marked at declaration time, but parameters are
1285 // an exception because it's technically only the call site that
1286 // actually requires the destructor.
1287 if (isa<ParmVarDecl>(var))
1288 S.FinalizeVarWithDestructor(var, rtype);
1289
John McCall6b5a61b2011-02-07 10:33:21 +00001290 // According to the blocks spec, the capture of a variable from
1291 // the stack requires a const copy constructor. This is not true
1292 // of the copy/move done to move a __block variable to the heap.
1293 type.addConst();
1294
1295 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1296 ExprResult result =
1297 S.PerformCopyInitialization(
1298 InitializedEntity::InitializeBlock(var->getLocation(),
1299 type, false),
1300 loc, S.Owned(declRef));
1301
1302 // Build a full-expression copy expression if initialization
1303 // succeeded and used a non-trivial constructor. Recover from
1304 // errors by pretending that the copy isn't necessary.
1305 if (!result.isInvalid() &&
1306 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1307 result = S.MaybeCreateExprWithCleanups(result);
1308 copyExpr = result.take();
1309 }
1310 }
1311
1312 // We're currently at the declarer; go back to the closure.
1313 functionScopesIndex++;
1314 BlockScopeInfo *blockScope =
1315 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1316
1317 // Build a valid capture in this scope.
1318 blockScope->Captures.push_back(
1319 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1320 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1321
1322 // Propagate that to inner captures if necessary.
1323 return propagateCapture(S, functionScopesIndex,
1324 blockScope->Captures.back());
1325}
1326
1327static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1328 const DeclarationNameInfo &NameInfo,
1329 bool byRef) {
1330 assert(isa<VarDecl>(vd) && "capturing non-variable");
1331
1332 VarDecl *var = cast<VarDecl>(vd);
1333 assert(var->hasLocalStorage() && "capturing non-local");
1334 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1335
1336 QualType exprType = var->getType().getNonReferenceType();
1337
1338 BlockDeclRefExpr *BDRE;
1339 if (!byRef) {
1340 // The variable will be bound by copy; make it const within the
1341 // closure, but record that this was done in the expression.
1342 bool constAdded = !exprType.isConstQualified();
1343 exprType.addConst();
1344
1345 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1346 NameInfo.getLoc(), false,
1347 constAdded);
1348 } else {
1349 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1350 NameInfo.getLoc(), true);
1351 }
1352
1353 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +00001354}
Chris Lattner639e2d32008-10-20 05:16:36 +00001355
John McCall60d7b3a2010-08-24 06:29:42 +00001356ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001357Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001358 SourceLocation Loc,
1359 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001360 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001361 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001362}
1363
John McCall76a40212011-02-09 01:13:10 +00001364/// BuildDeclRefExpr - Build an expression that references a
1365/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001366ExprResult
John McCall76a40212011-02-09 01:13:10 +00001367Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001368 const DeclarationNameInfo &NameInfo,
1369 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001370 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +00001371
John McCall7eb0a9e2010-11-24 05:12:34 +00001372 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00001373 SS? SS->getWithLocInContext(Context)
1374 : NestedNameSpecifierLoc(),
John McCall7eb0a9e2010-11-24 05:12:34 +00001375 D, NameInfo, Ty, VK);
1376
1377 // Just in case we're building an illegal pointer-to-member.
1378 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1379 E->setObjectKind(OK_BitField);
1380
1381 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001382}
1383
Abramo Bagnara25777432010-08-11 22:01:17 +00001384/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001385/// possibly a list of template arguments.
1386///
1387/// If this produces template arguments, it is permitted to call
1388/// DecomposeTemplateName.
1389///
1390/// This actually loses a lot of source location information for
1391/// non-standard name kinds; we should consider preserving that in
1392/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001393void
1394Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1395 TemplateArgumentListInfo &Buffer,
1396 DeclarationNameInfo &NameInfo,
1397 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001398 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1399 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1400 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1401
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001402 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall129e2df2009-11-30 22:42:35 +00001403 Id.TemplateId->getTemplateArgs(),
1404 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001405 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001406 TemplateArgsPtr.release();
1407
John McCall2b5289b2010-08-23 07:28:44 +00001408 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001409 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001410 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001411 TemplateArgs = &Buffer;
1412 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001413 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001414 TemplateArgs = 0;
1415 }
1416}
1417
John McCall578b69b2009-12-16 08:11:27 +00001418/// Diagnose an empty lookup.
1419///
1420/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001421bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001422 CorrectTypoContext CTC,
1423 TemplateArgumentListInfo *ExplicitTemplateArgs,
1424 Expr **Args, unsigned NumArgs) {
John McCall578b69b2009-12-16 08:11:27 +00001425 DeclarationName Name = R.getLookupName();
1426
John McCall578b69b2009-12-16 08:11:27 +00001427 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001428 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001429 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1430 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001431 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001432 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001433 diagnostic_suggest = diag::err_undeclared_use_suggest;
1434 }
John McCall578b69b2009-12-16 08:11:27 +00001435
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001436 // If the original lookup was an unqualified lookup, fake an
1437 // unqualified lookup. This is useful when (for example) the
1438 // original lookup would not have found something because it was a
1439 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001440 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001441 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001442 if (isa<CXXRecordDecl>(DC)) {
1443 LookupQualifiedName(R, DC);
1444
1445 if (!R.empty()) {
1446 // Don't give errors about ambiguities in this lookup.
1447 R.suppressDiagnostics();
1448
1449 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1450 bool isInstance = CurMethod &&
1451 CurMethod->isInstance() &&
1452 DC == CurMethod->getParent();
1453
1454 // Give a code modification hint to insert 'this->'.
1455 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1456 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001457 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001458 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1459 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001460 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001461 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001462 if (DepMethod) {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001463 Diag(R.getNameLoc(), diagnostic) << Name
1464 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1465 QualType DepThisType = DepMethod->getThisType(Context);
1466 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1467 R.getNameLoc(), DepThisType, false);
1468 TemplateArgumentListInfo TList;
1469 if (ULE->hasExplicitTemplateArgs())
1470 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001471
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001472 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00001473 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001474 CXXDependentScopeMemberExpr *DepExpr =
1475 CXXDependentScopeMemberExpr::Create(
1476 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001477 SS.getWithLocInContext(Context), NULL,
Francois Pichetf7400122011-09-04 23:00:48 +00001478 R.getLookupNameInfo(),
1479 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001480 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001481 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001482 // FIXME: we should be able to handle this case too. It is correct
1483 // to add this-> here. This is a workaround for PR7947.
1484 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001485 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001486 } else {
John McCall578b69b2009-12-16 08:11:27 +00001487 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001488 }
John McCall578b69b2009-12-16 08:11:27 +00001489
1490 // Do we really want to note all of these?
1491 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1492 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1493
1494 // Tell the callee to try to recover.
1495 return false;
1496 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001497
1498 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001499 }
1500 }
1501
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001502 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001503 TypoCorrection Corrected;
1504 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1505 S, &SS, NULL, false, CTC))) {
1506 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1507 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1508 R.setLookupName(Corrected.getCorrection());
1509
Hans Wennborg701d1e72011-07-12 08:45:31 +00001510 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001511 if (Corrected.isOverloaded()) {
1512 OverloadCandidateSet OCS(R.getNameLoc());
1513 OverloadCandidateSet::iterator Best;
1514 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1515 CDEnd = Corrected.end();
1516 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001517 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001518 dyn_cast<FunctionTemplateDecl>(*CD))
1519 AddTemplateOverloadCandidate(
1520 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1521 Args, NumArgs, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001522 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1523 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1524 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1525 Args, NumArgs, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001526 }
1527 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1528 case OR_Success:
1529 ND = Best->Function;
1530 break;
1531 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001532 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001533 }
1534 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001535 R.addDecl(ND);
1536 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001537 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001538 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1539 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001540 else
1541 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001542 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001543 << SS.getRange()
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001544 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1545 if (ND)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001546 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001547 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001548
1549 // Tell the callee to try to recover.
1550 return false;
1551 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001552
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001553 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001554 // FIXME: If we ended up with a typo for a type name or
1555 // Objective-C class name, we're in trouble because the parser
1556 // is in the wrong place to recover. Suggest the typo
1557 // correction, but don't make it a fix-it since we're not going
1558 // to recover well anyway.
1559 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001560 Diag(R.getNameLoc(), diagnostic_suggest)
1561 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001562 else
1563 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001564 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001565 << SS.getRange();
1566
1567 // Don't try to recover; it won't work.
1568 return true;
1569 }
1570 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001571 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001572 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001573 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001574 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001575 else
Douglas Gregord203a162010-01-01 00:15:04 +00001576 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001577 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001578 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001579 return true;
1580 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001581 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001582 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001583
1584 // Emit a special diagnostic for failed member lookups.
1585 // FIXME: computing the declaration context might fail here (?)
1586 if (!SS.isEmpty()) {
1587 Diag(R.getNameLoc(), diag::err_no_member)
1588 << Name << computeDeclContext(SS, false)
1589 << SS.getRange();
1590 return true;
1591 }
1592
John McCall578b69b2009-12-16 08:11:27 +00001593 // Give up, we can't recover.
1594 Diag(R.getNameLoc(), diagnostic) << Name;
1595 return true;
1596}
1597
John McCall60d7b3a2010-08-24 06:29:42 +00001598ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001599 CXXScopeSpec &SS,
1600 UnqualifiedId &Id,
1601 bool HasTrailingLParen,
1602 bool isAddressOfOperand) {
John McCallf7a1a742009-11-24 19:00:30 +00001603 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1604 "cannot be direct & operand and have a trailing lparen");
1605
1606 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001607 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001608
John McCall129e2df2009-11-30 22:42:35 +00001609 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001610
1611 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001612 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001613 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001614 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001615
Abramo Bagnara25777432010-08-11 22:01:17 +00001616 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001617 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001618 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001619
John McCallf7a1a742009-11-24 19:00:30 +00001620 // C++ [temp.dep.expr]p3:
1621 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001622 // -- an identifier that was declared with a dependent type,
1623 // (note: handled after lookup)
1624 // -- a template-id that is dependent,
1625 // (note: handled in BuildTemplateIdExpr)
1626 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001627 // -- a nested-name-specifier that contains a class-name that
1628 // names a dependent type.
1629 // Determine whether this is a member of an unknown specialization;
1630 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001631 bool DependentID = false;
1632 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1633 Name.getCXXNameType()->isDependentType()) {
1634 DependentID = true;
1635 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001636 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001637 if (RequireCompleteDeclContext(SS, DC))
1638 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001639 } else {
1640 DependentID = true;
1641 }
1642 }
1643
Chris Lattner337e5502011-02-18 01:27:55 +00001644 if (DependentID)
Abramo Bagnara25777432010-08-11 22:01:17 +00001645 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001646 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001647
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001648 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001649 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001650 LookupResult R(*this, NameInfo,
1651 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1652 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001653 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001654 // Lookup the template name again to correctly establish the context in
1655 // which it was found. This is really unfortunate as we already did the
1656 // lookup to determine that it was a template name in the first place. If
1657 // this becomes a performance hit, we can work harder to preserve those
1658 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001659 bool MemberOfUnknownSpecialization;
1660 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1661 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001662
1663 if (MemberOfUnknownSpecialization ||
1664 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1665 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1666 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001667 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001668 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001669 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001671 // If the result might be in a dependent base class, this is a dependent
1672 // id-expression.
1673 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1674 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1675 TemplateArgs);
1676
John McCallf7a1a742009-11-24 19:00:30 +00001677 // If this reference is in an Objective-C method, then we need to do
1678 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001679 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001680 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001681 if (E.isInvalid())
1682 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001683
Chris Lattner337e5502011-02-18 01:27:55 +00001684 if (Expr *Ex = E.takeAs<Expr>())
1685 return Owned(Ex);
1686
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001687 // for further use, this must be set to false if in class method.
1688 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001689 }
Chris Lattner8a934232008-03-31 00:36:02 +00001690 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001691
John McCallf7a1a742009-11-24 19:00:30 +00001692 if (R.isAmbiguous())
1693 return ExprError();
1694
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001695 // Determine whether this name might be a candidate for
1696 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001697 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001698
John McCallf7a1a742009-11-24 19:00:30 +00001699 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001700 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001701 // in C90, extension in C99, forbidden in C++).
1702 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1703 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1704 if (D) R.addDecl(D);
1705 }
1706
1707 // If this name wasn't predeclared and if this is not a function
1708 // call, diagnose the problem.
1709 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001710 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001711 return ExprError();
1712
1713 assert(!R.empty() &&
1714 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001715
1716 // If we found an Objective-C instance variable, let
1717 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001718 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001719 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1720 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001721 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001722 assert(E.isInvalid() || E.get());
1723 return move(E);
1724 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001725 }
1726 }
Mike Stump1eb44332009-09-09 15:08:12 +00001727
John McCallf7a1a742009-11-24 19:00:30 +00001728 // This is guaranteed from this point on.
1729 assert(!R.empty() || ADL);
1730
John McCallaa81e162009-12-01 22:10:20 +00001731 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001732 // C++ [class.mfct.non-static]p3:
1733 // When an id-expression that is not part of a class member access
1734 // syntax and not used to form a pointer to member is used in the
1735 // body of a non-static member function of class X, if name lookup
1736 // resolves the name in the id-expression to a non-static non-type
1737 // member of some class C, the id-expression is transformed into a
1738 // class member access expression using (*this) as the
1739 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001740 //
1741 // But we don't actually need to do this for '&' operands if R
1742 // resolved to a function or overloaded function set, because the
1743 // expression is ill-formed if it actually works out to be a
1744 // non-static member function:
1745 //
1746 // C++ [expr.ref]p4:
1747 // Otherwise, if E1.E2 refers to a non-static member function. . .
1748 // [t]he expression can be used only as the left-hand operand of a
1749 // member function call.
1750 //
1751 // There are other safeguards against such uses, but it's important
1752 // to get this right here so that we don't end up making a
1753 // spuriously dependent expression if we're inside a dependent
1754 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001755 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001756 bool MightBeImplicitMember;
1757 if (!isAddressOfOperand)
1758 MightBeImplicitMember = true;
1759 else if (!SS.isEmpty())
1760 MightBeImplicitMember = false;
1761 else if (R.isOverloadedResult())
1762 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001763 else if (R.isUnresolvableResult())
1764 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001765 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001766 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1767 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001768
1769 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001770 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001771 }
1772
John McCallf7a1a742009-11-24 19:00:30 +00001773 if (TemplateArgs)
1774 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001775
John McCallf7a1a742009-11-24 19:00:30 +00001776 return BuildDeclarationNameExpr(SS, R, ADL);
1777}
1778
John McCall129e2df2009-11-30 22:42:35 +00001779/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1780/// declaration name, generally during template instantiation.
1781/// There's a large number of things which don't need to be done along
1782/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001783ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001784Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001785 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001786 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001787 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001788 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001789
John McCall77bb1aa2010-05-01 00:40:08 +00001790 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001791 return ExprError();
1792
Abramo Bagnara25777432010-08-11 22:01:17 +00001793 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001794 LookupQualifiedName(R, DC);
1795
1796 if (R.isAmbiguous())
1797 return ExprError();
1798
1799 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001800 Diag(NameInfo.getLoc(), diag::err_no_member)
1801 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001802 return ExprError();
1803 }
1804
1805 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1806}
1807
1808/// LookupInObjCMethod - The parser has read a name in, and Sema has
1809/// detected that we're currently inside an ObjC method. Perform some
1810/// additional lookup.
1811///
1812/// Ideally, most of this would be done by lookup, but there's
1813/// actually quite a lot of extra work involved.
1814///
1815/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001816ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001817Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001818 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001819 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001820 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001821
John McCallf7a1a742009-11-24 19:00:30 +00001822 // There are two cases to handle here. 1) scoped lookup could have failed,
1823 // in which case we should look for an ivar. 2) scoped lookup could have
1824 // found a decl, but that decl is outside the current instance method (i.e.
1825 // a global variable). In these two cases, we do a lookup for an ivar with
1826 // this name, if the lookup sucedes, we replace it our current decl.
1827
1828 // If we're in a class method, we don't normally want to look for
1829 // ivars. But if we don't find anything else, and there's an
1830 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001831 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001832
1833 bool LookForIvars;
1834 if (Lookup.empty())
1835 LookForIvars = true;
1836 else if (IsClassMethod)
1837 LookForIvars = false;
1838 else
1839 LookForIvars = (Lookup.isSingleResult() &&
1840 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001841 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001842 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001843 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001844 ObjCInterfaceDecl *ClassDeclared;
1845 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1846 // Diagnose using an ivar in a class method.
1847 if (IsClassMethod)
1848 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1849 << IV->getDeclName());
1850
1851 // If we're referencing an invalid decl, just return this as a silent
1852 // error node. The error diagnostic was already emitted on the decl.
1853 if (IV->isInvalidDecl())
1854 return ExprError();
1855
1856 // Check if referencing a field with __attribute__((deprecated)).
1857 if (DiagnoseUseOfDecl(IV, Loc))
1858 return ExprError();
1859
1860 // Diagnose the use of an ivar outside of the declaring class.
1861 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1862 ClassDeclared != IFace)
1863 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1864
1865 // FIXME: This should use a new expr for a direct reference, don't
1866 // turn this into Self->ivar, just return a BareIVarExpr or something.
1867 IdentifierInfo &II = Context.Idents.get("self");
1868 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001869 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001870 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00001871 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00001872 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001873 SelfName, false, false);
1874 if (SelfExpr.isInvalid())
1875 return ExprError();
1876
John Wiegley429bb272011-04-08 18:41:53 +00001877 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1878 if (SelfExpr.isInvalid())
1879 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001880
John McCallf7a1a742009-11-24 19:00:30 +00001881 MarkDeclarationReferenced(Loc, IV);
1882 return Owned(new (Context)
1883 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00001884 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001885 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001886 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001887 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001888 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001889 ObjCInterfaceDecl *ClassDeclared;
1890 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1891 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1892 IFace == ClassDeclared)
1893 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1894 }
1895 }
1896
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001897 if (Lookup.empty() && II && AllowBuiltinCreation) {
1898 // FIXME. Consolidate this with similar code in LookupName.
1899 if (unsigned BuiltinID = II->getBuiltinID()) {
1900 if (!(getLangOptions().CPlusPlus &&
1901 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1902 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1903 S, Lookup.isForRedeclaration(),
1904 Lookup.getNameLoc());
1905 if (D) Lookup.addDecl(D);
1906 }
1907 }
1908 }
John McCallf7a1a742009-11-24 19:00:30 +00001909 // Sentinel value saying that we didn't do anything special.
1910 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001911}
John McCallba135432009-11-21 08:51:07 +00001912
John McCall6bb80172010-03-30 21:47:33 +00001913/// \brief Cast a base object to a member's actual type.
1914///
1915/// Logically this happens in three phases:
1916///
1917/// * First we cast from the base type to the naming class.
1918/// The naming class is the class into which we were looking
1919/// when we found the member; it's the qualifier type if a
1920/// qualifier was provided, and otherwise it's the base type.
1921///
1922/// * Next we cast from the naming class to the declaring class.
1923/// If the member we found was brought into a class's scope by
1924/// a using declaration, this is that class; otherwise it's
1925/// the class declaring the member.
1926///
1927/// * Finally we cast from the declaring class to the "true"
1928/// declaring class of the member. This conversion does not
1929/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00001930ExprResult
1931Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001932 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001933 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001934 NamedDecl *Member) {
1935 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1936 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00001937 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001938
Douglas Gregor5fccd362010-03-03 23:55:11 +00001939 QualType DestRecordType;
1940 QualType DestType;
1941 QualType FromRecordType;
1942 QualType FromType = From->getType();
1943 bool PointerConversions = false;
1944 if (isa<FieldDecl>(Member)) {
1945 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001946
Douglas Gregor5fccd362010-03-03 23:55:11 +00001947 if (FromType->getAs<PointerType>()) {
1948 DestType = Context.getPointerType(DestRecordType);
1949 FromRecordType = FromType->getPointeeType();
1950 PointerConversions = true;
1951 } else {
1952 DestType = DestRecordType;
1953 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001954 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001955 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1956 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00001957 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001958
Douglas Gregor5fccd362010-03-03 23:55:11 +00001959 DestType = Method->getThisType(Context);
1960 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001961
Douglas Gregor5fccd362010-03-03 23:55:11 +00001962 if (FromType->getAs<PointerType>()) {
1963 FromRecordType = FromType->getPointeeType();
1964 PointerConversions = true;
1965 } else {
1966 FromRecordType = FromType;
1967 DestType = DestRecordType;
1968 }
1969 } else {
1970 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00001971 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00001972 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001973
Douglas Gregor5fccd362010-03-03 23:55:11 +00001974 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00001975 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001976
Douglas Gregor5fccd362010-03-03 23:55:11 +00001977 // If the unqualified types are the same, no conversion is necessary.
1978 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00001979 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001980
John McCall6bb80172010-03-30 21:47:33 +00001981 SourceRange FromRange = From->getSourceRange();
1982 SourceLocation FromLoc = FromRange.getBegin();
1983
John McCall5baba9d2010-08-25 10:28:54 +00001984 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00001985
Douglas Gregor5fccd362010-03-03 23:55:11 +00001986 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001987 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00001988 // class name.
1989 //
1990 // If the member was a qualified name and the qualified referred to a
1991 // specific base subobject type, we'll cast to that intermediate type
1992 // first and then to the object in which the member is declared. That allows
1993 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1994 //
1995 // class Base { public: int x; };
1996 // class Derived1 : public Base { };
1997 // class Derived2 : public Base { };
1998 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1999 //
2000 // void VeryDerived::f() {
2001 // x = 17; // error: ambiguous base subobjects
2002 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2003 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002004 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002005 QualType QType = QualType(Qualifier->getAsType(), 0);
2006 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2007 assert(QType->isRecordType() && "lookup done with non-record type");
2008
2009 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2010
2011 // In C++98, the qualifier type doesn't actually have to be a base
2012 // type of the object type, in which case we just ignore it.
2013 // Otherwise build the appropriate casts.
2014 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002015 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002016 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002017 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002018 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002019
Douglas Gregor5fccd362010-03-03 23:55:11 +00002020 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002021 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002022 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2023 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002024
2025 FromType = QType;
2026 FromRecordType = QRecordType;
2027
2028 // If the qualifier type was the same as the destination type,
2029 // we're done.
2030 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002031 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002032 }
2033 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002034
John McCall6bb80172010-03-30 21:47:33 +00002035 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002036
John McCall6bb80172010-03-30 21:47:33 +00002037 // If we actually found the member through a using declaration, cast
2038 // down to the using declaration's type.
2039 //
2040 // Pointer equality is fine here because only one declaration of a
2041 // class ever has member declarations.
2042 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2043 assert(isa<UsingShadowDecl>(FoundDecl));
2044 QualType URecordType = Context.getTypeDeclType(
2045 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2046
2047 // We only need to do this if the naming-class to declaring-class
2048 // conversion is non-trivial.
2049 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2050 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002051 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002052 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002053 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002054 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002055
John McCall6bb80172010-03-30 21:47:33 +00002056 QualType UType = URecordType;
2057 if (PointerConversions)
2058 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002059 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2060 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002061 FromType = UType;
2062 FromRecordType = URecordType;
2063 }
2064
2065 // We don't do access control for the conversion from the
2066 // declaring class to the true declaring class.
2067 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002068 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002069
John McCallf871d0c2010-08-07 06:22:56 +00002070 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002071 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2072 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002073 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002074 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002075
John Wiegley429bb272011-04-08 18:41:53 +00002076 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2077 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002078}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002079
John McCallf7a1a742009-11-24 19:00:30 +00002080bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002081 const LookupResult &R,
2082 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002083 // Only when used directly as the postfix-expression of a call.
2084 if (!HasTrailingLParen)
2085 return false;
2086
2087 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002088 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002089 return false;
2090
2091 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002092 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002093 return false;
2094
2095 // Turn off ADL when we find certain kinds of declarations during
2096 // normal lookup:
2097 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2098 NamedDecl *D = *I;
2099
2100 // C++0x [basic.lookup.argdep]p3:
2101 // -- a declaration of a class member
2102 // Since using decls preserve this property, we check this on the
2103 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002104 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002105 return false;
2106
2107 // C++0x [basic.lookup.argdep]p3:
2108 // -- a block-scope function declaration that is not a
2109 // using-declaration
2110 // NOTE: we also trigger this for function templates (in fact, we
2111 // don't check the decl type at all, since all other decl types
2112 // turn off ADL anyway).
2113 if (isa<UsingShadowDecl>(D))
2114 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2115 else if (D->getDeclContext()->isFunctionOrMethod())
2116 return false;
2117
2118 // C++0x [basic.lookup.argdep]p3:
2119 // -- a declaration that is neither a function or a function
2120 // template
2121 // And also for builtin functions.
2122 if (isa<FunctionDecl>(D)) {
2123 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2124
2125 // But also builtin functions.
2126 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2127 return false;
2128 } else if (!isa<FunctionTemplateDecl>(D))
2129 return false;
2130 }
2131
2132 return true;
2133}
2134
2135
John McCallba135432009-11-21 08:51:07 +00002136/// Diagnoses obvious problems with the use of the given declaration
2137/// as an expression. This is only actually called for lookups that
2138/// were not overloaded, and it doesn't promise that the declaration
2139/// will in fact be used.
2140static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002141 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002142 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2143 return true;
2144 }
2145
2146 if (isa<ObjCInterfaceDecl>(D)) {
2147 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2148 return true;
2149 }
2150
2151 if (isa<NamespaceDecl>(D)) {
2152 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2153 return true;
2154 }
2155
2156 return false;
2157}
2158
John McCall60d7b3a2010-08-24 06:29:42 +00002159ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002160Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002161 LookupResult &R,
2162 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002163 // If this is a single, fully-resolved result and we don't need ADL,
2164 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002165 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002166 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2167 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002168
2169 // We only need to check the declaration if there's exactly one
2170 // result, because in the overloaded case the results can only be
2171 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002172 if (R.isSingleResult() &&
2173 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002174 return ExprError();
2175
John McCallc373d482010-01-27 01:50:18 +00002176 // Otherwise, just build an unresolved lookup expression. Suppress
2177 // any lookup-related diagnostics; we'll hash these out later, when
2178 // we've picked a target.
2179 R.suppressDiagnostics();
2180
John McCallba135432009-11-21 08:51:07 +00002181 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002182 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002183 SS.getWithLocInContext(Context),
2184 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002185 NeedsADL, R.isOverloadedResult(),
2186 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002187
2188 return Owned(ULE);
2189}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002190
John McCallba135432009-11-21 08:51:07 +00002191/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002192ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002193Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002194 const DeclarationNameInfo &NameInfo,
2195 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002196 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002197 assert(!isa<FunctionTemplateDecl>(D) &&
2198 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002199
Abramo Bagnara25777432010-08-11 22:01:17 +00002200 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002201 if (CheckDeclInExpr(*this, Loc, D))
2202 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002203
Douglas Gregor9af2f522009-12-01 16:58:18 +00002204 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2205 // Specifically diagnose references to class templates that are missing
2206 // a template argument list.
2207 Diag(Loc, diag::err_template_decl_ref)
2208 << Template << SS.getRange();
2209 Diag(Template->getLocation(), diag::note_template_decl_here);
2210 return ExprError();
2211 }
2212
2213 // Make sure that we're referring to a value.
2214 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2215 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002216 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002217 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002218 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002219 return ExprError();
2220 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002221
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002222 // Check whether this declaration can be used. Note that we suppress
2223 // this check when we're going to perform argument-dependent lookup
2224 // on this function name, because this might not be the function
2225 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002226 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002227 return ExprError();
2228
Steve Naroffdd972f22008-09-05 22:11:13 +00002229 // Only create DeclRefExpr's for valid Decl's.
2230 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002231 return ExprError();
2232
John McCall5808ce42011-02-03 08:15:49 +00002233 // Handle members of anonymous structs and unions. If we got here,
2234 // and the reference is to a class member indirect field, then this
2235 // must be the subject of a pointer-to-member expression.
2236 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2237 if (!indirectField->isCXXClassMember())
2238 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2239 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002240
Chris Lattner639e2d32008-10-20 05:16:36 +00002241 // If the identifier reference is inside a block, and it refers to a value
2242 // that is outside the block, create a BlockDeclRefExpr instead of a
2243 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2244 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002245 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002246 // We do not do this for things like enum constants, global variables, etc,
2247 // as they do not get snapshotted.
2248 //
John McCall6b5a61b2011-02-07 10:33:21 +00002249 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002250 case CR_Error:
2251 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002252
John McCall469a1eb2011-02-02 13:00:07 +00002253 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002254 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2255 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2256
2257 case CR_CaptureByRef:
2258 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2259 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002260
2261 case CR_NoCapture: {
2262 // If this reference is not in a block or if the referenced
2263 // variable is within the block, create a normal DeclRefExpr.
2264
2265 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002266 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002267
2268 switch (D->getKind()) {
2269 // Ignore all the non-ValueDecl kinds.
2270#define ABSTRACT_DECL(kind)
2271#define VALUE(type, base)
2272#define DECL(type, base) \
2273 case Decl::type:
2274#include "clang/AST/DeclNodes.inc"
2275 llvm_unreachable("invalid value decl kind");
2276 return ExprError();
2277
2278 // These shouldn't make it here.
2279 case Decl::ObjCAtDefsField:
2280 case Decl::ObjCIvar:
2281 llvm_unreachable("forming non-member reference to ivar?");
2282 return ExprError();
2283
2284 // Enum constants are always r-values and never references.
2285 // Unresolved using declarations are dependent.
2286 case Decl::EnumConstant:
2287 case Decl::UnresolvedUsingValue:
2288 valueKind = VK_RValue;
2289 break;
2290
2291 // Fields and indirect fields that got here must be for
2292 // pointer-to-member expressions; we just call them l-values for
2293 // internal consistency, because this subexpression doesn't really
2294 // exist in the high-level semantics.
2295 case Decl::Field:
2296 case Decl::IndirectField:
2297 assert(getLangOptions().CPlusPlus &&
2298 "building reference to field in C?");
2299
2300 // These can't have reference type in well-formed programs, but
2301 // for internal consistency we do this anyway.
2302 type = type.getNonReferenceType();
2303 valueKind = VK_LValue;
2304 break;
2305
2306 // Non-type template parameters are either l-values or r-values
2307 // depending on the type.
2308 case Decl::NonTypeTemplateParm: {
2309 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2310 type = reftype->getPointeeType();
2311 valueKind = VK_LValue; // even if the parameter is an r-value reference
2312 break;
2313 }
2314
2315 // For non-references, we need to strip qualifiers just in case
2316 // the template parameter was declared as 'const int' or whatever.
2317 valueKind = VK_RValue;
2318 type = type.getUnqualifiedType();
2319 break;
2320 }
2321
2322 case Decl::Var:
2323 // In C, "extern void blah;" is valid and is an r-value.
2324 if (!getLangOptions().CPlusPlus &&
2325 !type.hasQualifiers() &&
2326 type->isVoidType()) {
2327 valueKind = VK_RValue;
2328 break;
2329 }
2330 // fallthrough
2331
2332 case Decl::ImplicitParam:
2333 case Decl::ParmVar:
2334 // These are always l-values.
2335 valueKind = VK_LValue;
2336 type = type.getNonReferenceType();
2337 break;
2338
2339 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002340 const FunctionType *fty = type->castAs<FunctionType>();
2341
2342 // If we're referring to a function with an __unknown_anytype
2343 // result type, make the entire expression __unknown_anytype.
2344 if (fty->getResultType() == Context.UnknownAnyTy) {
2345 type = Context.UnknownAnyTy;
2346 valueKind = VK_RValue;
2347 break;
2348 }
2349
John McCall76a40212011-02-09 01:13:10 +00002350 // Functions are l-values in C++.
2351 if (getLangOptions().CPlusPlus) {
2352 valueKind = VK_LValue;
2353 break;
2354 }
2355
2356 // C99 DR 316 says that, if a function type comes from a
2357 // function definition (without a prototype), that type is only
2358 // used for checking compatibility. Therefore, when referencing
2359 // the function, we pretend that we don't have the full function
2360 // type.
John McCall755d8492011-04-12 00:42:48 +00002361 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2362 isa<FunctionProtoType>(fty))
2363 type = Context.getFunctionNoProtoType(fty->getResultType(),
2364 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002365
2366 // Functions are r-values in C.
2367 valueKind = VK_RValue;
2368 break;
2369 }
2370
2371 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002372 // If we're referring to a method with an __unknown_anytype
2373 // result type, make the entire expression __unknown_anytype.
2374 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002375 if (const FunctionProtoType *proto
2376 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002377 if (proto->getResultType() == Context.UnknownAnyTy) {
2378 type = Context.UnknownAnyTy;
2379 valueKind = VK_RValue;
2380 break;
2381 }
2382
John McCall76a40212011-02-09 01:13:10 +00002383 // C++ methods are l-values if static, r-values if non-static.
2384 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2385 valueKind = VK_LValue;
2386 break;
2387 }
2388 // fallthrough
2389
2390 case Decl::CXXConversion:
2391 case Decl::CXXDestructor:
2392 case Decl::CXXConstructor:
2393 valueKind = VK_RValue;
2394 break;
2395 }
2396
2397 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2398 }
2399
John McCall469a1eb2011-02-02 13:00:07 +00002400 }
John McCallf89e55a2010-11-18 06:31:45 +00002401
John McCall6b5a61b2011-02-07 10:33:21 +00002402 llvm_unreachable("unknown capture result");
2403 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002404}
2405
John McCall755d8492011-04-12 00:42:48 +00002406ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002407 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002408
Reid Spencer5f016e22007-07-11 17:01:13 +00002409 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002410 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002411 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2412 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2413 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002414 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002415
Chris Lattnerfa28b302008-01-12 08:14:25 +00002416 // Pre-defined identifiers are of type char[x], where x is the length of the
2417 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002418
Anders Carlsson3a082d82009-09-08 18:24:21 +00002419 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002420 if (!currentDecl && getCurBlock())
2421 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002422 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002423 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002424 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002425 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002426
Anders Carlsson773f3972009-09-11 01:22:35 +00002427 QualType ResTy;
2428 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2429 ResTy = Context.DependentTy;
2430 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002431 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002432
Anders Carlsson773f3972009-09-11 01:22:35 +00002433 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002434 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002435 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2436 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002437 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002438}
2439
John McCall60d7b3a2010-08-24 06:29:42 +00002440ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002441 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002442 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002443 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002444 if (Invalid)
2445 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002446
Benjamin Kramerddeea562010-02-27 13:44:12 +00002447 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002448 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002449 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002450 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002451
Chris Lattnere8337df2009-12-30 21:19:39 +00002452 QualType Ty;
2453 if (!getLangOptions().CPlusPlus)
2454 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2455 else if (Literal.isWide())
2456 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002457 else if (Literal.isUTF16())
2458 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2459 else if (Literal.isUTF32())
2460 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002461 else if (Literal.isMultiChar())
2462 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002463 else
2464 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002465
Douglas Gregor5cee1192011-07-27 05:40:30 +00002466 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2467 if (Literal.isWide())
2468 Kind = CharacterLiteral::Wide;
2469 else if (Literal.isUTF16())
2470 Kind = CharacterLiteral::UTF16;
2471 else if (Literal.isUTF32())
2472 Kind = CharacterLiteral::UTF32;
2473
2474 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2475 Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002476}
2477
John McCall60d7b3a2010-08-24 06:29:42 +00002478ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002479 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002480 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2481 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002482 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002483 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002484 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002485 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002486 }
Ted Kremenek28396602009-01-13 23:19:12 +00002487
Reid Spencer5f016e22007-07-11 17:01:13 +00002488 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002489 // Add padding so that NumericLiteralParser can overread by one character.
2490 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002491 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002492
Reid Spencer5f016e22007-07-11 17:01:13 +00002493 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002494 bool Invalid = false;
2495 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2496 if (Invalid)
2497 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002498
Mike Stump1eb44332009-09-09 15:08:12 +00002499 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002500 Tok.getLocation(), PP);
2501 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002502 return ExprError();
2503
Chris Lattner5d661452007-08-26 03:42:43 +00002504 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002505
Chris Lattner5d661452007-08-26 03:42:43 +00002506 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002507 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002508 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002509 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002510 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002511 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002512 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002513 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002514
2515 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2516
John McCall94c939d2009-12-24 09:08:04 +00002517 using llvm::APFloat;
2518 APFloat Val(Format);
2519
2520 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002521
2522 // Overflow is always an error, but underflow is only an error if
2523 // we underflowed to zero (APFloat reports denormals as underflow).
2524 if ((result & APFloat::opOverflow) ||
2525 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002526 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002527 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002528 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002529 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002530 APFloat::getLargest(Format).toString(buffer);
2531 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002532 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002533 APFloat::getSmallest(Format).toString(buffer);
2534 }
2535
2536 Diag(Tok.getLocation(), diagnostic)
2537 << Ty
Chris Lattner5f9e2722011-07-23 10:55:15 +00002538 << StringRef(buffer.data(), buffer.size());
John McCall94c939d2009-12-24 09:08:04 +00002539 }
2540
2541 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002542 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002543
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002544 if (Ty == Context.DoubleTy) {
2545 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002546 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002547 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2548 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002549 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002550 }
2551 }
Chris Lattner5d661452007-08-26 03:42:43 +00002552 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002553 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002554 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002555 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002556
Neil Boothb9449512007-08-29 22:00:19 +00002557 // long long is a C99 feature.
2558 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002559 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002560 Diag(Tok.getLocation(), diag::ext_longlong);
2561
Reid Spencer5f016e22007-07-11 17:01:13 +00002562 // Get the value in the widest-possible width.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002563 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002564
Reid Spencer5f016e22007-07-11 17:01:13 +00002565 if (Literal.GetIntegerValue(ResultVal)) {
2566 // If this value didn't fit into uintmax_t, warn and force to ull.
2567 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002568 Ty = Context.UnsignedLongLongTy;
2569 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002570 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002571 } else {
2572 // If this value fits into a ULL, try to figure out what else it fits into
2573 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002574
Reid Spencer5f016e22007-07-11 17:01:13 +00002575 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2576 // be an unsigned int.
2577 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2578
2579 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002580 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002581 if (!Literal.isLong && !Literal.isLongLong) {
2582 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002583 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002584
Reid Spencer5f016e22007-07-11 17:01:13 +00002585 // Does it fit in a unsigned int?
2586 if (ResultVal.isIntN(IntSize)) {
2587 // Does it fit in a signed int?
2588 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002589 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002590 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002591 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002592 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002593 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002594 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002595
Reid Spencer5f016e22007-07-11 17:01:13 +00002596 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002597 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002598 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002599
Reid Spencer5f016e22007-07-11 17:01:13 +00002600 // Does it fit in a unsigned long?
2601 if (ResultVal.isIntN(LongSize)) {
2602 // Does it fit in a signed long?
2603 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002604 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002605 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002606 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002607 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002608 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002609 }
2610
Reid Spencer5f016e22007-07-11 17:01:13 +00002611 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002612 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002613 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002614
Reid Spencer5f016e22007-07-11 17:01:13 +00002615 // Does it fit in a unsigned long long?
2616 if (ResultVal.isIntN(LongLongSize)) {
2617 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002618 // To be compatible with MSVC, hex integer literals ending with the
2619 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002620 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2621 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002622 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002623 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002624 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002625 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002626 }
2627 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002628
Reid Spencer5f016e22007-07-11 17:01:13 +00002629 // If we still couldn't decide a type, we probably have something that
2630 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002631 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002632 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002633 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002634 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002635 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002636
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002637 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002638 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002639 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002640 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002641 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002642
Chris Lattner5d661452007-08-26 03:42:43 +00002643 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2644 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002645 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002646 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002647
2648 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002649}
2650
John McCall60d7b3a2010-08-24 06:29:42 +00002651ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCall9ae2f072010-08-23 23:25:46 +00002652 SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002653 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002654 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002655}
2656
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002657static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2658 SourceLocation Loc,
2659 SourceRange ArgRange) {
2660 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2661 // scalar or vector data type argument..."
2662 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2663 // type (C99 6.2.5p18) or void.
2664 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2665 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2666 << T << ArgRange;
2667 return true;
2668 }
2669
2670 assert((T->isVoidType() || !T->isIncompleteType()) &&
2671 "Scalar types should always be complete");
2672 return false;
2673}
2674
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002675static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2676 SourceLocation Loc,
2677 SourceRange ArgRange,
2678 UnaryExprOrTypeTrait TraitKind) {
2679 // C99 6.5.3.4p1:
2680 if (T->isFunctionType()) {
2681 // alignof(function) is allowed as an extension.
2682 if (TraitKind == UETT_SizeOf)
2683 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2684 return false;
2685 }
2686
2687 // Allow sizeof(void)/alignof(void) as an extension.
2688 if (T->isVoidType()) {
2689 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2690 return false;
2691 }
2692
2693 return true;
2694}
2695
2696static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2697 SourceLocation Loc,
2698 SourceRange ArgRange,
2699 UnaryExprOrTypeTrait TraitKind) {
2700 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2701 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2702 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2703 << T << (TraitKind == UETT_SizeOf)
2704 << ArgRange;
2705 return true;
2706 }
2707
2708 return false;
2709}
2710
Chandler Carruth9d342d02011-05-26 08:53:10 +00002711/// \brief Check the constrains on expression operands to unary type expression
2712/// and type traits.
2713///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002714/// Completes any types necessary and validates the constraints on the operand
2715/// expression. The logic mostly mirrors the type-based overload, but may modify
2716/// the expression as it completes the type for that expression through template
2717/// instantiation, etc.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002718bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
2719 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002720 QualType ExprTy = Op->getType();
2721
2722 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2723 // the result is the size of the referenced type."
2724 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2725 // result shall be the alignment of the referenced type."
2726 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2727 ExprTy = Ref->getPointeeType();
2728
2729 if (ExprKind == UETT_VecStep)
2730 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2731 Op->getSourceRange());
2732
2733 // Whitelist some types as extensions
2734 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2735 Op->getSourceRange(), ExprKind))
2736 return false;
2737
2738 if (RequireCompleteExprType(Op,
2739 PDiag(diag::err_sizeof_alignof_incomplete_type)
2740 << ExprKind << Op->getSourceRange(),
2741 std::make_pair(SourceLocation(), PDiag(0))))
2742 return true;
2743
2744 // Completeing the expression's type may have changed it.
2745 ExprTy = Op->getType();
2746 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2747 ExprTy = Ref->getPointeeType();
2748
2749 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
2750 Op->getSourceRange(), ExprKind))
2751 return true;
2752
Nico Webercf739922011-06-15 02:47:03 +00002753 if (ExprKind == UETT_SizeOf) {
2754 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
2755 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2756 QualType OType = PVD->getOriginalType();
2757 QualType Type = PVD->getType();
2758 if (Type->isPointerType() && OType->isArrayType()) {
2759 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
2760 << Type << OType;
2761 Diag(PVD->getLocation(), diag::note_declared_at);
2762 }
2763 }
2764 }
2765 }
2766
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002767 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00002768}
2769
2770/// \brief Check the constraints on operands to unary expression and type
2771/// traits.
2772///
2773/// This will complete any types necessary, and validate the various constraints
2774/// on those operands.
2775///
Reid Spencer5f016e22007-07-11 17:01:13 +00002776/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002777/// C99 6.3.2.1p[2-4] all state:
2778/// Except when it is the operand of the sizeof operator ...
2779///
2780/// C++ [expr.sizeof]p4
2781/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2782/// standard conversions are not applied to the operand of sizeof.
2783///
2784/// This policy is followed for all of the unary trait expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002785bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2786 SourceLocation OpLoc,
2787 SourceRange ExprRange,
2788 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl28507842009-02-26 14:39:58 +00002789 if (exprType->isDependentType())
2790 return false;
2791
Sebastian Redl5d484e82009-11-23 17:18:46 +00002792 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2793 // the result is the size of the referenced type."
2794 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2795 // result shall be the alignment of the referenced type."
2796 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2797 exprType = Ref->getPointeeType();
2798
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002799 if (ExprKind == UETT_VecStep)
2800 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002801
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002802 // Whitelist some types as extensions
2803 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
2804 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00002805 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002806
Chris Lattner1efaa952009-04-24 00:30:45 +00002807 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002808 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002809 << ExprKind << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002810 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002811
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002812 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
2813 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00002814 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002815
Chris Lattner1efaa952009-04-24 00:30:45 +00002816 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002817}
2818
Chandler Carruth9d342d02011-05-26 08:53:10 +00002819static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00002820 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002821
Mike Stump1eb44332009-09-09 15:08:12 +00002822 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002823 if (isa<DeclRefExpr>(E))
2824 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002825
2826 // Cannot know anything else if the expression is dependent.
2827 if (E->isTypeDependent())
2828 return false;
2829
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002830 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002831 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2832 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002833 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002834 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002835
2836 // Alignment of a field access is always okay, so long as it isn't a
2837 // bit-field.
2838 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002839 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002840 return false;
2841
Chandler Carruth9d342d02011-05-26 08:53:10 +00002842 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002843}
2844
Chandler Carruth9d342d02011-05-26 08:53:10 +00002845bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002846 E = E->IgnoreParens();
2847
2848 // Cannot know anything else if the expression is dependent.
2849 if (E->isTypeDependent())
2850 return false;
2851
Chandler Carruth9d342d02011-05-26 08:53:10 +00002852 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00002853}
2854
Douglas Gregorba498172009-03-13 21:01:28 +00002855/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002856ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002857Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2858 SourceLocation OpLoc,
2859 UnaryExprOrTypeTrait ExprKind,
2860 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002861 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002862 return ExprError();
2863
John McCalla93c9342009-12-07 02:54:59 +00002864 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002865
Douglas Gregorba498172009-03-13 21:01:28 +00002866 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002867 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00002868 return ExprError();
2869
2870 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002871 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2872 Context.getSizeType(),
2873 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002874}
2875
2876/// \brief Build a sizeof or alignof expression given an expression
2877/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002878ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002879Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2880 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00002881 ExprResult PE = CheckPlaceholderExpr(E);
2882 if (PE.isInvalid())
2883 return ExprError();
2884
2885 E = PE.get();
2886
Douglas Gregorba498172009-03-13 21:01:28 +00002887 // Verify that the operand is valid.
2888 bool isInvalid = false;
2889 if (E->isTypeDependent()) {
2890 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002891 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002892 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002893 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002894 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002895 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002896 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00002897 isInvalid = true;
2898 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002899 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00002900 }
2901
2902 if (isInvalid)
2903 return ExprError();
2904
2905 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002906 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002907 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002908 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002909}
2910
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002911/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2912/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00002913/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00002914ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002915Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2916 UnaryExprOrTypeTrait ExprKind, bool isType,
2917 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002918 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002919 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002920
Sebastian Redl05189992008-11-11 17:56:53 +00002921 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00002922 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00002923 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002924 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002925 }
Sebastian Redl05189992008-11-11 17:56:53 +00002926
Douglas Gregorba498172009-03-13 21:01:28 +00002927 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002928 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregorba498172009-03-13 21:01:28 +00002929 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002930}
2931
John Wiegley429bb272011-04-08 18:41:53 +00002932static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall09431682010-11-18 19:01:18 +00002933 bool isReal) {
John Wiegley429bb272011-04-08 18:41:53 +00002934 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00002935 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002936
John McCallf6a16482010-12-04 03:47:34 +00002937 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00002938 if (V.get()->getObjectKind() != OK_Ordinary) {
2939 V = S.DefaultLvalueConversion(V.take());
2940 if (V.isInvalid())
2941 return QualType();
2942 }
John McCallf6a16482010-12-04 03:47:34 +00002943
Chris Lattnercc26ed72007-08-26 05:39:26 +00002944 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00002945 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002946 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002947
Chris Lattnercc26ed72007-08-26 05:39:26 +00002948 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00002949 if (V.get()->getType()->isArithmeticType())
2950 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002951
John McCall2cd11fe2010-10-12 02:09:17 +00002952 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00002953 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00002954 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00002955 if (PR.get() != V.get()) {
2956 V = move(PR);
John McCall09431682010-11-18 19:01:18 +00002957 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall2cd11fe2010-10-12 02:09:17 +00002958 }
2959
Chris Lattnercc26ed72007-08-26 05:39:26 +00002960 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00002961 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002962 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00002963 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00002964}
2965
2966
Reid Spencer5f016e22007-07-11 17:01:13 +00002967
John McCall60d7b3a2010-08-24 06:29:42 +00002968ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00002969Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002970 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00002971 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00002972 switch (Kind) {
2973 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00002974 case tok::plusplus: Opc = UO_PostInc; break;
2975 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002976 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002977
John McCall9ae2f072010-08-23 23:25:46 +00002978 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002979}
2980
John McCall60d7b3a2010-08-24 06:29:42 +00002981ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002982Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2983 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00002984 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00002985 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00002986 if (Result.isInvalid()) return ExprError();
2987 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002988
John McCall9ae2f072010-08-23 23:25:46 +00002989 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00002990
Douglas Gregor337c6b92008-11-19 17:17:41 +00002991 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002992 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002993 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00002994 Context.DependentTy,
2995 VK_LValue, OK_Ordinary,
2996 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002997 }
2998
Mike Stump1eb44332009-09-09 15:08:12 +00002999 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003000 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003001 LHSExp->getType()->isEnumeralType() ||
3002 RHSExp->getType()->isRecordType() ||
3003 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00003004 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003005 }
3006
John McCall9ae2f072010-08-23 23:25:46 +00003007 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003008}
3009
3010
John McCall60d7b3a2010-08-24 06:29:42 +00003011ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003012Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3013 Expr *Idx, SourceLocation RLoc) {
3014 Expr *LHSExp = Base;
3015 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003016
Chris Lattner12d9ff62007-07-16 00:14:47 +00003017 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003018 if (!LHSExp->getType()->getAs<VectorType>()) {
3019 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3020 if (Result.isInvalid())
3021 return ExprError();
3022 LHSExp = Result.take();
3023 }
3024 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3025 if (Result.isInvalid())
3026 return ExprError();
3027 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003028
Chris Lattner12d9ff62007-07-16 00:14:47 +00003029 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003030 ExprValueKind VK = VK_LValue;
3031 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003032
Reid Spencer5f016e22007-07-11 17:01:13 +00003033 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003034 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003035 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003036 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003037 Expr *BaseExpr, *IndexExpr;
3038 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003039 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3040 BaseExpr = LHSExp;
3041 IndexExpr = RHSExp;
3042 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003043 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003044 BaseExpr = LHSExp;
3045 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003046 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003047 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00003048 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00003049 BaseExpr = RHSExp;
3050 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003051 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003052 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003053 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003054 BaseExpr = LHSExp;
3055 IndexExpr = RHSExp;
3056 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003057 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003058 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003059 // Handle the uncommon case of "123[Ptr]".
3060 BaseExpr = RHSExp;
3061 IndexExpr = LHSExp;
3062 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003063 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003064 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003065 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003066 VK = LHSExp->getValueKind();
3067 if (VK != VK_RValue)
3068 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003069
Chris Lattner12d9ff62007-07-16 00:14:47 +00003070 // FIXME: need to deal with const...
3071 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003072 } else if (LHSTy->isArrayType()) {
3073 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003074 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003075 // wasn't promoted because of the C90 rule that doesn't
3076 // allow promoting non-lvalue arrays. Warn, then
3077 // force the promotion here.
3078 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3079 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003080 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3081 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003082 LHSTy = LHSExp->getType();
3083
3084 BaseExpr = LHSExp;
3085 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003086 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003087 } else if (RHSTy->isArrayType()) {
3088 // Same as previous, except for 123[f().a] case
3089 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3090 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003091 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3092 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003093 RHSTy = RHSExp->getType();
3094
3095 BaseExpr = RHSExp;
3096 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003097 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003098 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003099 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3100 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003101 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003102 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003103 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003104 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3105 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003106
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003107 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003108 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3109 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003110 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3111
Douglas Gregore7450f52009-03-24 19:52:54 +00003112 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003113 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3114 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003115 // incomplete types are not object types.
3116 if (ResultType->isFunctionType()) {
3117 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3118 << ResultType << BaseExpr->getSourceRange();
3119 return ExprError();
3120 }
Mike Stump1eb44332009-09-09 15:08:12 +00003121
Abramo Bagnara46358452010-09-13 06:50:07 +00003122 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3123 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003124 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3125 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003126
3127 // C forbids expressions of unqualified void type from being l-values.
3128 // See IsCForbiddenLValueType.
3129 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003130 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003131 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003132 PDiag(diag::err_subscript_incomplete_type)
3133 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003134 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003135
Chris Lattner1efaa952009-04-24 00:30:45 +00003136 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003137 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003138 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3139 << ResultType << BaseExpr->getSourceRange();
3140 return ExprError();
3141 }
Mike Stump1eb44332009-09-09 15:08:12 +00003142
John McCall09431682010-11-18 19:01:18 +00003143 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003144 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003145
Mike Stumpeed9cac2009-02-19 03:04:26 +00003146 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003147 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003148}
3149
John McCall60d7b3a2010-08-24 06:29:42 +00003150ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003151 FunctionDecl *FD,
3152 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003153 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003154 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003155 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003156 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003157 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003158 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003159 return ExprError();
3160 }
3161
3162 if (Param->hasUninstantiatedDefaultArg()) {
3163 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003164
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003165 // Instantiate the expression.
3166 MultiLevelTemplateArgumentList ArgList
3167 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003168
Nico Weber08e41a62010-11-29 18:19:25 +00003169 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003170 = ArgList.getInnermost();
3171 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3172 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003173
Nico Weber08e41a62010-11-29 18:19:25 +00003174 ExprResult Result;
3175 {
3176 // C++ [dcl.fct.default]p5:
3177 // The names in the [default argument] expression are bound, and
3178 // the semantic constraints are checked, at the point where the
3179 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003180 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00003181 Result = SubstExpr(UninstExpr, ArgList);
3182 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003183 if (Result.isInvalid())
3184 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003185
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003186 // Check the expression as an initializer for the parameter.
3187 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003188 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003189 InitializationKind Kind
3190 = InitializationKind::CreateCopy(Param->getLocation(),
3191 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3192 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003193
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003194 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3195 Result = InitSeq.Perform(*this, Entity, Kind,
3196 MultiExprArg(*this, &ResultE, 1));
3197 if (Result.isInvalid())
3198 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003199
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003200 // Build the default argument expression.
3201 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3202 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003203 }
3204
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003205 // If the default expression creates temporaries, we need to
3206 // push them to the current stack of expression temporaries so they'll
3207 // be properly destroyed.
3208 // FIXME: We should really be rebuilding the default argument with new
3209 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003210 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3211 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3212 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3213 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3214 ExprTemporaries.push_back(Temporary);
John McCallf85e1932011-06-15 23:02:42 +00003215 ExprNeedsCleanups = true;
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003216 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003217
3218 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003219 // Just mark all of the declarations in this potentially-evaluated expression
3220 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003221 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00003222 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003223}
3224
Douglas Gregor88a35142008-12-22 05:46:06 +00003225/// ConvertArgumentsForCall - Converts the arguments specified in
3226/// Args/NumArgs to the parameter types of the function FDecl with
3227/// function prototype Proto. Call is the call expression itself, and
3228/// Fn is the function expression. For a C++ member function, this
3229/// routine does not attempt to convert the object argument. Returns
3230/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003231bool
3232Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003233 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003234 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003235 Expr **Args, unsigned NumArgs,
3236 SourceLocation RParenLoc) {
John McCall8e10f3b2011-02-26 05:39:39 +00003237 // Bail out early if calling a builtin with custom typechecking.
3238 // We don't need to do this in the
3239 if (FDecl)
3240 if (unsigned ID = FDecl->getBuiltinID())
3241 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3242 return false;
3243
Mike Stumpeed9cac2009-02-19 03:04:26 +00003244 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003245 // assignment, to the types of the corresponding parameter, ...
3246 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003247 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003248
Douglas Gregor88a35142008-12-22 05:46:06 +00003249 // If too few arguments are available (and we don't have default
3250 // arguments for the remaining parameters), don't make the call.
3251 if (NumArgs < NumArgsInProto) {
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003252 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) {
3253 Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003254 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00003255 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003256
3257 // Emit the location of the prototype.
3258 if (FDecl && !FDecl->getBuiltinID())
3259 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3260 << FDecl;
3261
3262 return true;
3263 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003264 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003265 }
3266
3267 // If too many are passed and not variadic, error on the extras and drop
3268 // them.
3269 if (NumArgs > NumArgsInProto) {
3270 if (!Proto->isVariadic()) {
3271 Diag(Args[NumArgsInProto]->getLocStart(),
3272 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003273 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00003274 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00003275 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3276 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003277
3278 // Emit the location of the prototype.
3279 if (FDecl && !FDecl->getBuiltinID())
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003280 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3281 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003282
Douglas Gregor88a35142008-12-22 05:46:06 +00003283 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003284 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003285 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003286 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003287 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003288 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003289 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003290 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3291 if (Fn->getType()->isBlockPointerType())
3292 CallType = VariadicBlock; // Block
3293 else if (isa<MemberExpr>(Fn))
3294 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003295 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003296 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003297 if (Invalid)
3298 return true;
3299 unsigned TotalNumArgs = AllArgs.size();
3300 for (unsigned i = 0; i < TotalNumArgs; ++i)
3301 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003302
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003303 return false;
3304}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003305
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003306bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3307 FunctionDecl *FDecl,
3308 const FunctionProtoType *Proto,
3309 unsigned FirstProtoArg,
3310 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003311 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003312 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003313 unsigned NumArgsInProto = Proto->getNumArgs();
3314 unsigned NumArgsToCheck = NumArgs;
3315 bool Invalid = false;
3316 if (NumArgs != NumArgsInProto)
3317 // Use default arguments for missing arguments
3318 NumArgsToCheck = NumArgsInProto;
3319 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003320 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003321 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003322 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003323
Douglas Gregor88a35142008-12-22 05:46:06 +00003324 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003325 if (ArgIx < NumArgs) {
3326 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003327
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003328 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3329 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003330 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003331 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003332 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003333
Douglas Gregora188ff22009-12-22 16:09:06 +00003334 // Pass the argument
3335 ParmVarDecl *Param = 0;
3336 if (FDecl && i < FDecl->getNumParams())
3337 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003338
Douglas Gregora188ff22009-12-22 16:09:06 +00003339 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003340 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003341 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3342 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003343 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003344 SourceLocation(),
3345 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00003346 if (ArgE.isInvalid())
3347 return true;
3348
3349 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003350 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003351 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003352
John McCall60d7b3a2010-08-24 06:29:42 +00003353 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003354 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003355 if (ArgExpr.isInvalid())
3356 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003357
Anders Carlsson56c5e332009-08-25 03:49:14 +00003358 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003359 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003360
3361 // Check for array bounds violations for each argument to the call. This
3362 // check only triggers warnings when the argument isn't a more complex Expr
3363 // with its own checking, such as a BinaryOperator.
3364 CheckArrayAccess(Arg);
3365
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003366 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003367 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003368
Douglas Gregor88a35142008-12-22 05:46:06 +00003369 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003370 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003371
3372 // Assume that extern "C" functions with variadic arguments that
3373 // return __unknown_anytype aren't *really* variadic.
3374 if (Proto->getResultType() == Context.UnknownAnyTy &&
3375 FDecl && FDecl->isExternC()) {
3376 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3377 ExprResult arg;
3378 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3379 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3380 else
3381 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3382 Invalid |= arg.isInvalid();
3383 AllArgs.push_back(arg.take());
3384 }
3385
3386 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3387 } else {
3388 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003389 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3390 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003391 Invalid |= Arg.isInvalid();
3392 AllArgs.push_back(Arg.take());
3393 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003394 }
3395 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003396 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003397}
3398
John McCall755d8492011-04-12 00:42:48 +00003399/// Given a function expression of unknown-any type, try to rebuild it
3400/// to have a function type.
3401static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3402
Steve Narofff69936d2007-09-16 03:34:24 +00003403/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003404/// This provides the location of the left/right parens and a list of comma
3405/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003406ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003407Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003408 MultiExprArg args, SourceLocation RParenLoc,
3409 Expr *ExecConfig) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003410 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003411
3412 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003413 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003414 if (Result.isInvalid()) return ExprError();
3415 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003416
John McCall9ae2f072010-08-23 23:25:46 +00003417 Expr **Args = args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003418
Douglas Gregor88a35142008-12-22 05:46:06 +00003419 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003420 // If this is a pseudo-destructor expression, build the call immediately.
3421 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3422 if (NumArgs > 0) {
3423 // Pseudo-destructor calls should not have any arguments.
3424 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003425 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003426 SourceRange(Args[0]->getLocStart(),
3427 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003428
Douglas Gregora71d8192009-09-04 17:36:40 +00003429 NumArgs = 0;
3430 }
Mike Stump1eb44332009-09-09 15:08:12 +00003431
Douglas Gregora71d8192009-09-04 17:36:40 +00003432 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00003433 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003434 }
Mike Stump1eb44332009-09-09 15:08:12 +00003435
Douglas Gregor17330012009-02-04 15:01:18 +00003436 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003437 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003438 // FIXME: Will need to cache the results of name lookup (including ADL) in
3439 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003440 bool Dependent = false;
3441 if (Fn->isTypeDependent())
3442 Dependent = true;
3443 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3444 Dependent = true;
3445
Peter Collingbournee08ce652011-02-09 21:07:24 +00003446 if (Dependent) {
3447 if (ExecConfig) {
3448 return Owned(new (Context) CUDAKernelCallExpr(
3449 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3450 Context.DependentTy, VK_RValue, RParenLoc));
3451 } else {
3452 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3453 Context.DependentTy, VK_RValue,
3454 RParenLoc));
3455 }
3456 }
Douglas Gregor17330012009-02-04 15:01:18 +00003457
3458 // Determine whether this is a call to an object (C++ [over.call.object]).
3459 if (Fn->getType()->isRecordType())
3460 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003461 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003462
John McCall755d8492011-04-12 00:42:48 +00003463 if (Fn->getType() == Context.UnknownAnyTy) {
3464 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3465 if (result.isInvalid()) return ExprError();
3466 Fn = result.take();
3467 }
3468
John McCall864c0412011-04-26 20:42:42 +00003469 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00003470 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003471 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003472 }
John McCall864c0412011-04-26 20:42:42 +00003473 }
John McCall129e2df2009-11-30 22:42:35 +00003474
John McCall864c0412011-04-26 20:42:42 +00003475 // Check for overloaded calls. This can happen even in C due to extensions.
3476 if (Fn->getType() == Context.OverloadTy) {
3477 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3478
3479 // We aren't supposed to apply this logic if there's an '&' involved.
3480 if (!find.IsAddressOfOperand) {
3481 OverloadExpr *ovl = find.Expression;
3482 if (isa<UnresolvedLookupExpr>(ovl)) {
3483 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3484 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3485 RParenLoc, ExecConfig);
3486 } else {
John McCallaa81e162009-12-01 22:10:20 +00003487 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003488 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003489 }
3490 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003491 }
3492
Douglas Gregorfa047642009-02-04 00:32:51 +00003493 // If we're directly calling a function, get the appropriate declaration.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003494
Eli Friedmanefa42f72009-12-26 03:35:45 +00003495 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003496
John McCall3b4294e2009-12-16 12:17:52 +00003497 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003498 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3499 if (UnOp->getOpcode() == UO_AddrOf)
3500 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3501
John McCall3b4294e2009-12-16 12:17:52 +00003502 if (isa<DeclRefExpr>(NakedFn))
3503 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003504 else if (isa<MemberExpr>(NakedFn))
3505 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003506
Peter Collingbournee08ce652011-02-09 21:07:24 +00003507 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3508 ExecConfig);
3509}
3510
3511ExprResult
3512Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3513 MultiExprArg execConfig, SourceLocation GGGLoc) {
3514 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3515 if (!ConfigDecl)
3516 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3517 << "cudaConfigureCall");
3518 QualType ConfigQTy = ConfigDecl->getType();
3519
3520 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3521 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3522
3523 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCallaa81e162009-12-01 22:10:20 +00003524}
3525
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003526/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3527///
3528/// __builtin_astype( value, dst type )
3529///
3530ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
3531 SourceLocation BuiltinLoc,
3532 SourceLocation RParenLoc) {
3533 ExprValueKind VK = VK_RValue;
3534 ExprObjectKind OK = OK_Ordinary;
3535 QualType DstTy = GetTypeFromParser(destty);
3536 QualType SrcTy = expr->getType();
3537 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3538 return ExprError(Diag(BuiltinLoc,
3539 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003540 << DstTy
3541 << SrcTy
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003542 << expr->getSourceRange());
Richard Trieu67e29332011-08-02 04:35:43 +00003543 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc,
3544 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003545}
3546
John McCall3b4294e2009-12-16 12:17:52 +00003547/// BuildResolvedCallExpr - Build a call to a resolved expression,
3548/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003549/// unary-convert to an expression of function-pointer or
3550/// block-pointer type.
3551///
3552/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003553ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003554Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3555 SourceLocation LParenLoc,
3556 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003557 SourceLocation RParenLoc,
3558 Expr *Config) {
John McCallaa81e162009-12-01 22:10:20 +00003559 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3560
Chris Lattner04421082008-04-08 04:40:51 +00003561 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00003562 ExprResult Result = UsualUnaryConversions(Fn);
3563 if (Result.isInvalid())
3564 return ExprError();
3565 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00003566
Chris Lattner925e60d2007-12-28 05:29:59 +00003567 // Make the call expr early, before semantic checks. This guarantees cleanup
3568 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00003569 CallExpr *TheCall;
3570 if (Config) {
3571 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3572 cast<CallExpr>(Config),
3573 Args, NumArgs,
3574 Context.BoolTy,
3575 VK_RValue,
3576 RParenLoc);
3577 } else {
3578 TheCall = new (Context) CallExpr(Context, Fn,
3579 Args, NumArgs,
3580 Context.BoolTy,
3581 VK_RValue,
3582 RParenLoc);
3583 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003584
John McCall8e10f3b2011-02-26 05:39:39 +00003585 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3586
3587 // Bail out early if calling a builtin with custom typechecking.
3588 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3589 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3590
John McCall1de4d4e2011-04-07 08:22:57 +00003591 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00003592 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00003593 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00003594 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3595 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00003596 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00003597 if (FuncT == 0)
3598 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3599 << Fn->getType() << Fn->getSourceRange());
3600 } else if (const BlockPointerType *BPT =
3601 Fn->getType()->getAs<BlockPointerType>()) {
3602 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3603 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00003604 // Handle calls to expressions of unknown-any type.
3605 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00003606 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003607 if (rewrite.isInvalid()) return ExprError();
3608 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00003609 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003610 goto retry;
3611 }
3612
Sebastian Redl0eb23302009-01-19 00:08:26 +00003613 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3614 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00003615 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003616
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003617 if (getLangOptions().CUDA) {
3618 if (Config) {
3619 // CUDA: Kernel calls must be to global functions
3620 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3621 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3622 << FDecl->getName() << Fn->getSourceRange());
3623
3624 // CUDA: Kernel function must have 'void' return type
3625 if (!FuncT->getResultType()->isVoidType())
3626 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3627 << Fn->getType() << Fn->getSourceRange());
3628 }
3629 }
3630
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003631 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003632 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00003633 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003634 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003635 return ExprError();
3636
Chris Lattner925e60d2007-12-28 05:29:59 +00003637 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003638 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00003639 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003640
Douglas Gregor72564e72009-02-26 23:50:07 +00003641 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00003642 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003643 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003644 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003645 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003646 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003647
Douglas Gregor74734d52009-04-02 15:37:10 +00003648 if (FDecl) {
3649 // Check if we have too few/too many template arguments, based
3650 // on our knowledge of the function definition.
3651 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00003652 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003653 const FunctionProtoType *Proto
3654 = Def->getType()->getAs<FunctionProtoType>();
3655 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003656 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3657 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003658 }
Douglas Gregor46542412010-10-25 20:39:23 +00003659
3660 // If the function we're calling isn't a function prototype, but we have
3661 // a function prototype from a prior declaratiom, use that prototype.
3662 if (!FDecl->hasPrototype())
3663 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00003664 }
3665
Steve Naroffb291ab62007-08-28 23:30:39 +00003666 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003667 for (unsigned i = 0; i != NumArgs; i++) {
3668 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00003669
3670 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003671 InitializedEntity Entity
3672 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00003673 Proto->getArgType(i),
3674 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00003675 ExprResult ArgE = PerformCopyInitialization(Entity,
3676 SourceLocation(),
3677 Owned(Arg));
3678 if (ArgE.isInvalid())
3679 return true;
3680
3681 Arg = ArgE.takeAs<Expr>();
3682
3683 } else {
John Wiegley429bb272011-04-08 18:41:53 +00003684 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3685
3686 if (ArgE.isInvalid())
3687 return true;
3688
3689 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00003690 }
3691
Douglas Gregor0700bbf2010-10-26 05:45:40 +00003692 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3693 Arg->getType(),
3694 PDiag(diag::err_call_incomplete_argument)
3695 << Arg->getSourceRange()))
3696 return ExprError();
3697
Chris Lattner925e60d2007-12-28 05:29:59 +00003698 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003699 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003700 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003701
Douglas Gregor88a35142008-12-22 05:46:06 +00003702 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3703 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003704 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3705 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003706
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003707 // Check for sentinels
3708 if (NDecl)
3709 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003710
Chris Lattner59907c42007-08-10 20:18:51 +00003711 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003712 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003713 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003714 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003715
John McCall8e10f3b2011-02-26 05:39:39 +00003716 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00003717 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00003718 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003719 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003720 return ExprError();
3721 }
Chris Lattner59907c42007-08-10 20:18:51 +00003722
John McCall9ae2f072010-08-23 23:25:46 +00003723 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00003724}
3725
John McCall60d7b3a2010-08-24 06:29:42 +00003726ExprResult
John McCallb3d87482010-08-24 05:47:05 +00003727Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00003728 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003729 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00003730 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003731 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00003732
3733 TypeSourceInfo *TInfo;
3734 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3735 if (!TInfo)
3736 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3737
John McCall9ae2f072010-08-23 23:25:46 +00003738 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00003739}
3740
John McCall60d7b3a2010-08-24 06:29:42 +00003741ExprResult
John McCall42f56b52010-01-18 19:35:47 +00003742Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00003743 SourceLocation RParenLoc, Expr *literalExpr) {
John McCall42f56b52010-01-18 19:35:47 +00003744 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00003745
Eli Friedman6223c222008-05-20 05:22:08 +00003746 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00003747 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3748 PDiag(diag::err_illegal_decl_array_incomplete_type)
3749 << SourceRange(LParenLoc,
3750 literalExpr->getSourceRange().getEnd())))
3751 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003752 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003753 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3754 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003755 } else if (!literalType->isDependentType() &&
3756 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003757 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003758 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003759 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003760 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003761
Douglas Gregor99a2e602009-12-16 01:38:02 +00003762 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003763 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003764 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00003765 = InitializationKind::CreateCStyleCast(LParenLoc,
3766 SourceRange(LParenLoc, RParenLoc));
Eli Friedman08544622009-12-22 02:35:53 +00003767 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00003768 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00003769 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00003770 &literalType);
3771 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003772 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00003773 literalExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00003774
Chris Lattner371f2582008-12-04 23:50:19 +00003775 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003776 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003777 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003778 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003779 }
Eli Friedman08544622009-12-22 02:35:53 +00003780
John McCallf89e55a2010-11-18 06:31:45 +00003781 // In C, compound literals are l-values for some reason.
3782 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3783
Douglas Gregor751ec9b2011-06-17 04:59:12 +00003784 return MaybeBindToTemporary(
3785 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3786 VK, literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003787}
3788
John McCall60d7b3a2010-08-24 06:29:42 +00003789ExprResult
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003790Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003791 SourceLocation RBraceLoc) {
3792 unsigned NumInit = initlist.size();
John McCall9ae2f072010-08-23 23:25:46 +00003793 Expr **InitList = initlist.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003794
Steve Naroff08d92e42007-09-15 18:49:24 +00003795 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003796 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003797
Ted Kremenek709210f2010-04-13 23:39:13 +00003798 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3799 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003800 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003801 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003802}
3803
John McCallf3ea8cf2010-11-14 08:17:51 +00003804/// Prepares for a scalar cast, performing all the necessary stages
3805/// except the final cast and returning the kind required.
John Wiegley429bb272011-04-08 18:41:53 +00003806static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00003807 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3808 // Also, callers should have filtered out the invalid cases with
3809 // pointers. Everything else should be possible.
3810
John Wiegley429bb272011-04-08 18:41:53 +00003811 QualType SrcTy = Src.get()->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00003812 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00003813 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00003814
John McCalldaa8e4e2010-11-15 09:13:47 +00003815 switch (SrcTy->getScalarTypeKind()) {
3816 case Type::STK_MemberPointer:
3817 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003818
John McCalldaa8e4e2010-11-15 09:13:47 +00003819 case Type::STK_Pointer:
3820 switch (DestTy->getScalarTypeKind()) {
3821 case Type::STK_Pointer:
3822 return DestTy->isObjCObjectPointerType() ?
John McCallf3ea8cf2010-11-14 08:17:51 +00003823 CK_AnyPointerToObjCPointerCast :
3824 CK_BitCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003825 case Type::STK_Bool:
3826 return CK_PointerToBoolean;
3827 case Type::STK_Integral:
3828 return CK_PointerToIntegral;
3829 case Type::STK_Floating:
3830 case Type::STK_FloatingComplex:
3831 case Type::STK_IntegralComplex:
3832 case Type::STK_MemberPointer:
3833 llvm_unreachable("illegal cast from pointer");
3834 }
3835 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003836
John McCalldaa8e4e2010-11-15 09:13:47 +00003837 case Type::STK_Bool: // casting from bool is like casting from an integer
3838 case Type::STK_Integral:
3839 switch (DestTy->getScalarTypeKind()) {
3840 case Type::STK_Pointer:
Richard Trieu67e29332011-08-02 04:35:43 +00003841 if (Src.get()->isNullPointerConstant(S.Context,
3842 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00003843 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00003844 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00003845 case Type::STK_Bool:
3846 return CK_IntegralToBoolean;
3847 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00003848 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003849 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00003850 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00003851 case Type::STK_IntegralComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003852 Src = S.ImpCastExprToType(Src.take(),
3853 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003854 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00003855 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003856 case Type::STK_FloatingComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003857 Src = S.ImpCastExprToType(Src.take(),
3858 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003859 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00003860 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003861 case Type::STK_MemberPointer:
3862 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003863 }
3864 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003865
John McCalldaa8e4e2010-11-15 09:13:47 +00003866 case Type::STK_Floating:
3867 switch (DestTy->getScalarTypeKind()) {
3868 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00003869 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003870 case Type::STK_Bool:
3871 return CK_FloatingToBoolean;
3872 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00003873 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00003874 case Type::STK_FloatingComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003875 Src = S.ImpCastExprToType(Src.take(),
3876 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003877 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00003878 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003879 case Type::STK_IntegralComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003880 Src = S.ImpCastExprToType(Src.take(),
3881 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003882 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00003883 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003884 case Type::STK_Pointer:
3885 llvm_unreachable("valid float->pointer cast?");
3886 case Type::STK_MemberPointer:
3887 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003888 }
3889 break;
3890
John McCalldaa8e4e2010-11-15 09:13:47 +00003891 case Type::STK_FloatingComplex:
3892 switch (DestTy->getScalarTypeKind()) {
3893 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003894 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003895 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003896 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00003897 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003898 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00003899 if (S.Context.hasSameType(ET, DestTy))
3900 return CK_FloatingComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00003901 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00003902 return CK_FloatingCast;
3903 }
John McCalldaa8e4e2010-11-15 09:13:47 +00003904 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00003905 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00003906 case Type::STK_Integral:
Richard Trieu67e29332011-08-02 04:35:43 +00003907 Src = S.ImpCastExprToType(Src.take(),
3908 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003909 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00003910 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00003911 case Type::STK_Pointer:
3912 llvm_unreachable("valid complex float->pointer cast?");
3913 case Type::STK_MemberPointer:
3914 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003915 }
3916 break;
3917
John McCalldaa8e4e2010-11-15 09:13:47 +00003918 case Type::STK_IntegralComplex:
3919 switch (DestTy->getScalarTypeKind()) {
3920 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003921 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003922 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003923 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00003924 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003925 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00003926 if (S.Context.hasSameType(ET, DestTy))
3927 return CK_IntegralComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00003928 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00003929 return CK_IntegralCast;
3930 }
John McCalldaa8e4e2010-11-15 09:13:47 +00003931 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00003932 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00003933 case Type::STK_Floating:
Richard Trieu67e29332011-08-02 04:35:43 +00003934 Src = S.ImpCastExprToType(Src.take(),
3935 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003936 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00003937 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00003938 case Type::STK_Pointer:
3939 llvm_unreachable("valid complex int->pointer cast?");
3940 case Type::STK_MemberPointer:
3941 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003942 }
3943 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00003944 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003945
John McCallf3ea8cf2010-11-14 08:17:51 +00003946 llvm_unreachable("Unhandled scalar cast");
3947 return CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00003948}
3949
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003950/// CheckCastTypes - Check type constraints for casting between types.
John McCallf85e1932011-06-15 23:02:42 +00003951ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
3952 QualType castType, Expr *castExpr,
3953 CastKind& Kind, ExprValueKind &VK,
John Wiegley429bb272011-04-08 18:41:53 +00003954 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall1de4d4e2011-04-07 08:22:57 +00003955 if (castExpr->getType() == Context.UnknownAnyTy)
3956 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
3957
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003958 if (getLangOptions().CPlusPlus)
John McCallf85e1932011-06-15 23:02:42 +00003959 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor40749ee2010-11-03 00:35:38 +00003960 castExpr->getLocEnd()),
John McCallf89e55a2010-11-18 06:31:45 +00003961 castType, VK, castExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003962 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003963
John McCallfb8721c2011-04-10 19:13:55 +00003964 assert(!castExpr->getType()->isPlaceholderType());
3965
John McCallf89e55a2010-11-18 06:31:45 +00003966 // We only support r-value casts in C.
3967 VK = VK_RValue;
3968
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003969 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3970 // type needs to be scalar.
3971 if (castType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00003972 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley429bb272011-04-08 18:41:53 +00003973 ExprResult castExprRes = IgnoredValueConversions(castExpr);
3974 if (castExprRes.isInvalid())
3975 return ExprError();
3976 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00003977
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003978 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00003979 Kind = CK_ToVoid;
John Wiegley429bb272011-04-08 18:41:53 +00003980 return Owned(castExpr);
Anders Carlssonebeaf202009-10-16 02:35:04 +00003981 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003982
John Wiegley429bb272011-04-08 18:41:53 +00003983 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
3984 if (castExprRes.isInvalid())
3985 return ExprError();
3986 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00003987
Eli Friedman8d438082010-07-17 20:43:49 +00003988 if (RequireCompleteType(TyR.getBegin(), castType,
3989 diag::err_typecheck_cast_to_incomplete))
John Wiegley429bb272011-04-08 18:41:53 +00003990 return ExprError();
Eli Friedman8d438082010-07-17 20:43:49 +00003991
Anders Carlssonebeaf202009-10-16 02:35:04 +00003992 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003993 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003994 (castType->isStructureType() || castType->isUnionType())) {
3995 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003996 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003997 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3998 << castType << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003999 Kind = CK_NoOp;
John Wiegley429bb272011-04-08 18:41:53 +00004000 return Owned(castExpr);
Anders Carlssonc3516322009-10-16 02:48:28 +00004001 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004002
Anders Carlssonc3516322009-10-16 02:48:28 +00004003 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004004 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00004005 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004006 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004007 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004008 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004009 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00004010 castExpr->getType()) &&
4011 !Field->isUnnamedBitfield()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004012 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4013 << castExpr->getSourceRange();
4014 break;
4015 }
4016 }
John Wiegley429bb272011-04-08 18:41:53 +00004017 if (Field == FieldEnd) {
4018 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004019 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004020 return ExprError();
4021 }
John McCall2de56d12010-08-25 11:45:40 +00004022 Kind = CK_ToUnion;
John Wiegley429bb272011-04-08 18:41:53 +00004023 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004024 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004025
Anders Carlssonc3516322009-10-16 02:48:28 +00004026 // Reject any other conversions to non-scalar types.
John Wiegley429bb272011-04-08 18:41:53 +00004027 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlssonc3516322009-10-16 02:48:28 +00004028 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004029 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00004030 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004031
John McCallf3ea8cf2010-11-14 08:17:51 +00004032 // The type we're casting to is known to be a scalar or vector.
4033
4034 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004035 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00004036 !castExpr->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004037 Diag(castExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004038 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00004039 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004040 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00004041 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004042
4043 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00004044 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004045
Anton Yartsevd06fea82011-03-27 09:32:40 +00004046 if (castType->isVectorType()) {
4047 if (castType->getAs<VectorType>()->getVectorKind() ==
4048 VectorType::AltiVecVector &&
4049 (castExpr->getType()->isIntegerType() ||
4050 castExpr->getType()->isFloatingType())) {
4051 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004052 return Owned(castExpr);
4053 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
4054 return ExprError();
Anton Yartsevd06fea82011-03-27 09:32:40 +00004055 } else
John Wiegley429bb272011-04-08 18:41:53 +00004056 return Owned(castExpr);
Anton Yartsevd06fea82011-03-27 09:32:40 +00004057 }
John Wiegley429bb272011-04-08 18:41:53 +00004058 if (castExpr->getType()->isVectorType()) {
4059 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
4060 return ExprError();
4061 else
4062 return Owned(castExpr);
4063 }
Anders Carlssonc3516322009-10-16 02:48:28 +00004064
John McCallf3ea8cf2010-11-14 08:17:51 +00004065 // The source and target types are both scalars, i.e.
4066 // - arithmetic types (fundamental, enum, and complex)
4067 // - all kinds of pointers
4068 // Note that member pointers were filtered out with C++, above.
4069
John Wiegley429bb272011-04-08 18:41:53 +00004070 if (isa<ObjCSelectorExpr>(castExpr)) {
4071 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4072 return ExprError();
4073 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004074
John McCallf3ea8cf2010-11-14 08:17:51 +00004075 // If either type is a pointer, the other type has to be either an
4076 // integer or a pointer.
John McCallf85e1932011-06-15 23:02:42 +00004077 QualType castExprType = castExpr->getType();
Anders Carlssonc3516322009-10-16 02:48:28 +00004078 if (!castType->isArithmeticType()) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00004079 if (!castExprType->isIntegralType(Context) &&
John Wiegley429bb272011-04-08 18:41:53 +00004080 castExprType->isArithmeticType()) {
4081 Diag(castExpr->getLocStart(),
4082 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00004083 << castExprType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004084 return ExprError();
4085 }
Eli Friedman41826bb2009-05-01 02:23:58 +00004086 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004087 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
4088 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00004089 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004090 return ExprError();
4091 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004092 }
Anders Carlsson82debc72009-10-18 18:12:03 +00004093
John McCallf85e1932011-06-15 23:02:42 +00004094 if (getLangOptions().ObjCAutoRefCount) {
4095 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
4096 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
4097 castType, castExpr, CCK_CStyleCast);
4098
4099 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
4100 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
4101 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4102 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4103 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4104 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4105 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
4106 Diag(castExpr->getLocStart(),
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00004107 diag::err_typecheck_incompatible_ownership)
John McCallf85e1932011-06-15 23:02:42 +00004108 << castExprType << castType << AA_Casting
4109 << castExpr->getSourceRange();
4110
4111 return ExprError();
4112 }
4113 }
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00004114 }
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00004115 else if (!CheckObjCARCUnavailableWeakConversion(castType, castExprType)) {
4116 Diag(castExpr->getLocStart(),
Fariborz Jahanian82007c32011-07-08 17:41:42 +00004117 diag::err_arc_convesion_of_weak_unavailable) << 1
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00004118 << castExprType << castType
4119 << castExpr->getSourceRange();
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00004120 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00004121 }
4122 }
4123
John Wiegley429bb272011-04-08 18:41:53 +00004124 castExprRes = Owned(castExpr);
4125 Kind = PrepareScalarCast(*this, castExprRes, castType);
4126 if (castExprRes.isInvalid())
4127 return ExprError();
4128 castExpr = castExprRes.take();
John McCallb7f4ffe2010-08-12 21:44:57 +00004129
John McCallf3ea8cf2010-11-14 08:17:51 +00004130 if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00004131 CheckCastAlign(castExpr, castType, TyR);
4132
John Wiegley429bb272011-04-08 18:41:53 +00004133 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004134}
4135
Anders Carlssonc3516322009-10-16 02:48:28 +00004136bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004137 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004138 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004139
Anders Carlssona64db8f2007-11-27 05:51:55 +00004140 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004141 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004142 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004143 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004144 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004145 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004146 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004147 } else
4148 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004149 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004150 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004151
John McCall2de56d12010-08-25 11:45:40 +00004152 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004153 return false;
4154}
4155
John Wiegley429bb272011-04-08 18:41:53 +00004156ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4157 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004158 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004159
Anders Carlsson16a89042009-10-16 05:23:41 +00004160 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004161
Nate Begeman9b10da62009-06-27 22:05:55 +00004162 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4163 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00004164 if (SrcTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004165 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
4166 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004167 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004168 return ExprError();
4169 }
John McCall2de56d12010-08-25 11:45:40 +00004170 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004171 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004172 }
4173
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004174 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004175 // conversion will take place first from scalar to elt type, and then
4176 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004177 if (SrcTy->isPointerType())
4178 return Diag(R.getBegin(),
4179 diag::err_invalid_conversion_between_vector_and_scalar)
4180 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004181
4182 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004183 ExprResult CastExprRes = Owned(CastExpr);
4184 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4185 if (CastExprRes.isInvalid())
4186 return ExprError();
4187 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004188
John McCall2de56d12010-08-25 11:45:40 +00004189 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004190 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004191}
4192
John McCall60d7b3a2010-08-24 06:29:42 +00004193ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004194Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4195 Declarator &D, ParsedType &Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004196 SourceLocation RParenLoc, Expr *castExpr) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004197 assert(!D.isInvalidType() && (castExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004198 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004199
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004200 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, castExpr->getType());
4201 if (D.isInvalidType())
4202 return ExprError();
4203
4204 if (getLangOptions().CPlusPlus) {
4205 // Check that there are no default arguments (C++ only).
4206 CheckExtraCXXDefaultArguments(D);
4207 }
4208
4209 QualType castType = castTInfo->getType();
4210 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004211
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004212 bool isVectorLiteral = false;
4213
4214 // Check for an altivec or OpenCL literal,
4215 // i.e. all the elements are integer constants.
4216 ParenExpr *PE = dyn_cast<ParenExpr>(castExpr);
4217 ParenListExpr *PLE = dyn_cast<ParenListExpr>(castExpr);
4218 if (getLangOptions().AltiVec && castType->isVectorType() && (PE || PLE)) {
4219 if (PLE && PLE->getNumExprs() == 0) {
4220 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4221 return ExprError();
4222 }
4223 if (PE || PLE->getNumExprs() == 1) {
4224 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4225 if (!E->getType()->isVectorType())
4226 isVectorLiteral = true;
4227 }
4228 else
4229 isVectorLiteral = true;
4230 }
4231
4232 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4233 // then handle it as such.
4234 if (isVectorLiteral)
4235 return BuildVectorLiteral(LParenLoc, RParenLoc, castExpr, castTInfo);
4236
Nate Begeman2ef13e52009-08-10 23:49:36 +00004237 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004238 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4239 // sequence of BinOp comma operators.
4240 if (isa<ParenListExpr>(castExpr)) {
4241 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, castExpr);
4242 if (Result.isInvalid()) return ExprError();
4243 castExpr = Result.take();
4244 }
John McCallb042fdf2010-01-15 18:56:44 +00004245
John McCall9ae2f072010-08-23 23:25:46 +00004246 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004247}
4248
John McCall60d7b3a2010-08-24 06:29:42 +00004249ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00004250Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004251 SourceLocation RParenLoc, Expr *castExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004252 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00004253 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00004254 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +00004255 ExprResult CastResult =
John McCallf85e1932011-06-15 23:02:42 +00004256 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
4257 castExpr, Kind, VK, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +00004258 if (CastResult.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004259 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004260 castExpr = CastResult.take();
Anders Carlsson0aebc812009-09-09 21:33:21 +00004261
Richard Trieu67e29332011-08-02 04:35:43 +00004262 return Owned(CStyleCastExpr::Create(
4263 Context, Ty->getType().getNonLValueExprType(Context), VK, Kind, castExpr,
4264 &BasePath, Ty, LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00004265}
4266
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004267ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4268 SourceLocation RParenLoc, Expr *E,
4269 TypeSourceInfo *TInfo) {
4270 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4271 "Expected paren or paren list expression");
4272
4273 Expr **exprs;
4274 unsigned numExprs;
4275 Expr *subExpr;
4276 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4277 exprs = PE->getExprs();
4278 numExprs = PE->getNumExprs();
4279 } else {
4280 subExpr = cast<ParenExpr>(E)->getSubExpr();
4281 exprs = &subExpr;
4282 numExprs = 1;
4283 }
4284
4285 QualType Ty = TInfo->getType();
4286 assert(Ty->isVectorType() && "Expected vector type");
4287
Chris Lattner5f9e2722011-07-23 10:55:15 +00004288 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004289 const VectorType *VTy = Ty->getAs<VectorType>();
4290 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4291
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004292 // '(...)' form of vector initialization in AltiVec: the number of
4293 // initializers must be one or must match the size of the vector.
4294 // If a single value is specified in the initializer then it will be
4295 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004296 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004297 // The number of initializers must be one or must match the size of the
4298 // vector. If a single value is specified in the initializer then it will
4299 // be replicated to all the components of the vector
4300 if (numExprs == 1) {
4301 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4302 ExprResult Literal = Owned(exprs[0]);
4303 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4304 PrepareScalarCast(*this, Literal, ElemTy));
4305 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4306 }
4307 else if (numExprs < numElems) {
4308 Diag(E->getExprLoc(),
4309 diag::err_incorrect_number_of_vector_initializers);
4310 return ExprError();
4311 }
4312 else
4313 for (unsigned i = 0, e = numExprs; i != e; ++i)
4314 initExprs.push_back(exprs[i]);
4315 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004316 else {
4317 // For OpenCL, when the number of initializers is a single value,
4318 // it will be replicated to all components of the vector.
4319 if (getLangOptions().OpenCL &&
4320 VTy->getVectorKind() == VectorType::GenericVector &&
4321 numExprs == 1) {
4322 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4323 ExprResult Literal = Owned(exprs[0]);
4324 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4325 PrepareScalarCast(*this, Literal, ElemTy));
4326 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4327 }
4328
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004329 for (unsigned i = 0, e = numExprs; i != e; ++i)
4330 initExprs.push_back(exprs[i]);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004331 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004332 // FIXME: This means that pretty-printing the final AST will produce curly
4333 // braces instead of the original commas.
4334 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4335 &initExprs[0],
4336 initExprs.size(), RParenLoc);
4337 initE->setType(Ty);
4338 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4339}
4340
Nate Begeman2ef13e52009-08-10 23:49:36 +00004341/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4342/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004343ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004344Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004345 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4346 if (!E)
4347 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00004348
John McCall60d7b3a2010-08-24 06:29:42 +00004349 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004350
Nate Begeman2ef13e52009-08-10 23:49:36 +00004351 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004352 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4353 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004354
John McCall9ae2f072010-08-23 23:25:46 +00004355 if (Result.isInvalid()) return ExprError();
4356
4357 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004358}
4359
John McCall60d7b3a2010-08-24 06:29:42 +00004360ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00004361 SourceLocation R,
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004362 MultiExprArg Val) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004363 unsigned nexprs = Val.size();
4364 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004365 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4366 Expr *expr;
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004367 if (nexprs == 1)
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004368 expr = new (Context) ParenExpr(L, R, exprs[0]);
4369 else
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004370 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4371 exprs[nexprs-1]->getType());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004372 return Owned(expr);
4373}
4374
Chandler Carruth82214a82011-02-18 23:54:50 +00004375/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004376/// constant and the other is not a pointer. Returns true if a diagnostic is
4377/// emitted.
Chandler Carruth82214a82011-02-18 23:54:50 +00004378bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
4379 SourceLocation QuestionLoc) {
4380 Expr *NullExpr = LHS;
4381 Expr *NonPointerExpr = RHS;
4382 Expr::NullPointerConstantKind NullKind =
4383 NullExpr->isNullPointerConstant(Context,
4384 Expr::NPC_ValueDependentIsNotNull);
4385
4386 if (NullKind == Expr::NPCK_NotNull) {
4387 NullExpr = RHS;
4388 NonPointerExpr = LHS;
4389 NullKind =
4390 NullExpr->isNullPointerConstant(Context,
4391 Expr::NPC_ValueDependentIsNotNull);
4392 }
4393
4394 if (NullKind == Expr::NPCK_NotNull)
4395 return false;
4396
4397 if (NullKind == Expr::NPCK_ZeroInteger) {
4398 // In this case, check to make sure that we got here from a "NULL"
4399 // string in the source code.
4400 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004401 SourceLocation loc = NullExpr->getExprLoc();
4402 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004403 return false;
4404 }
4405
4406 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4407 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4408 << NonPointerExpr->getType() << DiagType
4409 << NonPointerExpr->getSourceRange();
4410 return true;
4411}
4412
Richard Trieu26f96072011-09-02 01:51:02 +00004413/// \brief Return false if the condition expression is valid, true otherwise.
4414static bool checkCondition(Sema &S, Expr *Cond) {
4415 QualType CondTy = Cond->getType();
4416
4417 // C99 6.5.15p2
4418 if (CondTy->isScalarType()) return false;
4419
4420 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4421 if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4422 return false;
4423
4424 // Emit the proper error message.
4425 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4426 diag::err_typecheck_cond_expect_scalar :
4427 diag::err_typecheck_cond_expect_scalar_or_vector)
4428 << CondTy;
4429 return true;
4430}
4431
4432/// \brief Return false if the two expressions can be converted to a vector,
4433/// true otherwise
4434static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4435 ExprResult &RHS,
4436 QualType CondTy) {
4437 // Both operands should be of scalar type.
4438 if (!LHS.get()->getType()->isScalarType()) {
4439 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4440 << CondTy;
4441 return true;
4442 }
4443 if (!RHS.get()->getType()->isScalarType()) {
4444 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4445 << CondTy;
4446 return true;
4447 }
4448
4449 // Implicity convert these scalars to the type of the condition.
4450 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4451 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4452 return false;
4453}
4454
4455/// \brief Handle when one or both operands are void type.
4456static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4457 ExprResult &RHS) {
4458 Expr *LHSExpr = LHS.get();
4459 Expr *RHSExpr = RHS.get();
4460
4461 if (!LHSExpr->getType()->isVoidType())
4462 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4463 << RHSExpr->getSourceRange();
4464 if (!RHSExpr->getType()->isVoidType())
4465 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4466 << LHSExpr->getSourceRange();
4467 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4468 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4469 return S.Context.VoidTy;
4470}
4471
4472/// \brief Return false if the NullExpr can be promoted to PointerTy,
4473/// true otherwise.
4474static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4475 QualType PointerTy) {
4476 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4477 !NullExpr.get()->isNullPointerConstant(S.Context,
4478 Expr::NPC_ValueDependentIsNull))
4479 return true;
4480
4481 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4482 return false;
4483}
4484
4485/// \brief Checks compatibility between two pointers and return the resulting
4486/// type.
4487static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4488 ExprResult &RHS,
4489 SourceLocation Loc) {
4490 QualType LHSTy = LHS.get()->getType();
4491 QualType RHSTy = RHS.get()->getType();
4492
4493 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4494 // Two identical pointers types are always compatible.
4495 return LHSTy;
4496 }
4497
4498 QualType lhptee, rhptee;
4499
4500 // Get the pointee types.
4501 if (LHSTy->isBlockPointerType()) {
4502 lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4503 rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
4504 } else {
4505 lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4506 rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4507 }
4508
4509 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4510 rhptee.getUnqualifiedType())) {
4511 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4512 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4513 << RHS.get()->getSourceRange();
4514 // In this situation, we assume void* type. No especially good
4515 // reason, but this is what gcc does, and we do have to pick
4516 // to get a consistent AST.
4517 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4518 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4519 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4520 return incompatTy;
4521 }
4522
4523 // The pointer types are compatible.
4524 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4525 // differently qualified versions of compatible types, the result type is
4526 // a pointer to an appropriately qualified version of the *composite*
4527 // type.
4528 // FIXME: Need to calculate the composite type.
4529 // FIXME: Need to add qualifiers
4530
4531 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4532 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4533 return LHSTy;
4534}
4535
4536/// \brief Return the resulting type when the operands are both block pointers.
4537static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4538 ExprResult &LHS,
4539 ExprResult &RHS,
4540 SourceLocation Loc) {
4541 QualType LHSTy = LHS.get()->getType();
4542 QualType RHSTy = RHS.get()->getType();
4543
4544 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4545 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4546 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4547 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4548 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4549 return destType;
4550 }
4551 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4552 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4553 << RHS.get()->getSourceRange();
4554 return QualType();
4555 }
4556
4557 // We have 2 block pointer types.
4558 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4559}
4560
4561/// \brief Return the resulting type when the operands are both pointers.
4562static QualType
4563checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4564 ExprResult &RHS,
4565 SourceLocation Loc) {
4566 // get the pointer types
4567 QualType LHSTy = LHS.get()->getType();
4568 QualType RHSTy = RHS.get()->getType();
4569
4570 // get the "pointed to" types
4571 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4572 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4573
4574 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4575 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4576 // Figure out necessary qualifiers (C99 6.5.15p6)
4577 QualType destPointee
4578 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4579 QualType destType = S.Context.getPointerType(destPointee);
4580 // Add qualifiers if necessary.
4581 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4582 // Promote to void*.
4583 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4584 return destType;
4585 }
4586 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4587 QualType destPointee
4588 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4589 QualType destType = S.Context.getPointerType(destPointee);
4590 // Add qualifiers if necessary.
4591 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4592 // Promote to void*.
4593 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4594 return destType;
4595 }
4596
4597 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4598}
4599
4600/// \brief Return false if the first expression is not an integer and the second
4601/// expression is not a pointer, true otherwise.
4602static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4603 Expr* PointerExpr, SourceLocation Loc,
4604 bool isIntFirstExpr) {
4605 if (!PointerExpr->getType()->isPointerType() ||
4606 !Int.get()->getType()->isIntegerType())
4607 return false;
4608
4609 Expr *Expr1 = isIntFirstExpr ? Int.get() : PointerExpr;
4610 Expr *Expr2 = isIntFirstExpr ? PointerExpr : Int.get();
4611
4612 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4613 << Expr1->getType() << Expr2->getType()
4614 << Expr1->getSourceRange() << Expr2->getSourceRange();
4615 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4616 CK_IntegralToPointer);
4617 return true;
4618}
4619
Sebastian Redl28507842009-02-26 14:39:58 +00004620/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4621/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004622/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004623QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4624 ExprResult &RHS, ExprValueKind &VK,
4625 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004626 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004627
John McCallfb8721c2011-04-10 19:13:55 +00004628 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00004629 if (!lhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004630 LHS = move(lhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004631
John McCallfb8721c2011-04-10 19:13:55 +00004632 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00004633 if (!rhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004634 RHS = move(rhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004635
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004636 // C++ is sufficiently different to merit its own checker.
4637 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004638 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004639
4640 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004641 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004642
John Wiegley429bb272011-04-08 18:41:53 +00004643 Cond = UsualUnaryConversions(Cond.take());
4644 if (Cond.isInvalid())
4645 return QualType();
4646 LHS = UsualUnaryConversions(LHS.take());
4647 if (LHS.isInvalid())
4648 return QualType();
4649 RHS = UsualUnaryConversions(RHS.take());
4650 if (RHS.isInvalid())
4651 return QualType();
4652
4653 QualType CondTy = Cond.get()->getType();
4654 QualType LHSTy = LHS.get()->getType();
4655 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004656
Reid Spencer5f016e22007-07-11 17:01:13 +00004657 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00004658 if (checkCondition(*this, Cond.get()))
4659 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004660
Chris Lattner70d67a92008-01-06 22:42:25 +00004661 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004662 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004663 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004664
Nate Begeman6155d732010-09-20 22:41:17 +00004665 // OpenCL: If the condition is a vector, and both operands are scalar,
4666 // attempt to implicity convert them to the vector type to act like the
4667 // built in select.
Richard Trieu26f96072011-09-02 01:51:02 +00004668 if (getLangOptions().OpenCL && CondTy->isVectorType())
4669 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00004670 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00004671
Chris Lattner70d67a92008-01-06 22:42:25 +00004672 // If both operands have arithmetic type, do the usual arithmetic conversions
4673 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004674 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4675 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004676 if (LHS.isInvalid() || RHS.isInvalid())
4677 return QualType();
4678 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004679 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004680
Chris Lattner70d67a92008-01-06 22:42:25 +00004681 // If both operands are the same structure or union type, the result is that
4682 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004683 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4684 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004685 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004686 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004687 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004688 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004689 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004690 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004691
Chris Lattner70d67a92008-01-06 22:42:25 +00004692 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004693 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004694 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004695 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00004696 }
Richard Trieu26f96072011-09-02 01:51:02 +00004697
Steve Naroffb6d54e52008-01-08 01:11:38 +00004698 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4699 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00004700 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4701 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004702
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004703 // All objective-c pointer type analysis is done here.
4704 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4705 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00004706 if (LHS.isInvalid() || RHS.isInvalid())
4707 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004708 if (!compositeType.isNull())
4709 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004710
4711
Steve Naroff7154a772009-07-01 14:36:47 +00004712 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00004713 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4714 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4715 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004716
Steve Naroff7154a772009-07-01 14:36:47 +00004717 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00004718 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4719 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4720 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004721
John McCall404cd162010-11-13 01:35:44 +00004722 // GCC compatibility: soften pointer/integer mismatch. Note that
4723 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00004724 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4725 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00004726 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004727 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4728 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00004729 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004730
Chandler Carruth82214a82011-02-18 23:54:50 +00004731 // Emit a better diagnostic if one of the expressions is a null pointer
4732 // constant and the other is not a pointer type. In this case, the user most
4733 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00004734 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00004735 return QualType();
4736
Chris Lattner70d67a92008-01-06 22:42:25 +00004737 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004738 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00004739 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4740 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004741 return QualType();
4742}
4743
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004744/// FindCompositeObjCPointerType - Helper method to find composite type of
4745/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00004746QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00004747 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00004748 QualType LHSTy = LHS.get()->getType();
4749 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004750
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004751 // Handle things like Class and struct objc_class*. Here we case the result
4752 // to the pseudo-builtin, because that will be implicitly cast back to the
4753 // redefinition type if an attempt is made to access its fields.
4754 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004755 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004756 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004757 return LHSTy;
4758 }
4759 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004760 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004761 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004762 return RHSTy;
4763 }
4764 // And the same for struct objc_object* / id
4765 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004766 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004767 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004768 return LHSTy;
4769 }
4770 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004771 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004772 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004773 return RHSTy;
4774 }
4775 // And the same for struct objc_selector* / SEL
4776 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004777 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004778 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004779 return LHSTy;
4780 }
4781 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004782 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004783 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004784 return RHSTy;
4785 }
4786 // Check constraints for Objective-C object pointers types.
4787 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004788
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004789 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4790 // Two identical object pointer types are always compatible.
4791 return LHSTy;
4792 }
4793 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4794 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4795 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004796
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004797 // If both operands are interfaces and either operand can be
4798 // assigned to the other, use that type as the composite
4799 // type. This allows
4800 // xxx ? (A*) a : (B*) b
4801 // where B is a subclass of A.
4802 //
4803 // Additionally, as for assignment, if either type is 'id'
4804 // allow silent coercion. Finally, if the types are
4805 // incompatible then make sure to use 'id' as the composite
4806 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004807
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004808 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4809 // It could return the composite type.
4810 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4811 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4812 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4813 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4814 } else if ((LHSTy->isObjCQualifiedIdType() ||
4815 RHSTy->isObjCQualifiedIdType()) &&
4816 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4817 // Need to handle "id<xx>" explicitly.
4818 // GCC allows qualified id and any Objective-C type to devolve to
4819 // id. Currently localizing to here until clear this should be
4820 // part of ObjCQualifiedIdTypesAreCompatible.
4821 compositeType = Context.getObjCIdType();
4822 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4823 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004824 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004825 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4826 ;
4827 else {
4828 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4829 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00004830 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004831 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00004832 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4833 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004834 return incompatTy;
4835 }
4836 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00004837 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4838 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004839 return compositeType;
4840 }
4841 // Check Objective-C object pointer types and 'void *'
4842 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4843 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4844 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4845 QualType destPointee
4846 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4847 QualType destType = Context.getPointerType(destPointee);
4848 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004849 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004850 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004851 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004852 return destType;
4853 }
4854 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4855 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4856 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4857 QualType destPointee
4858 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4859 QualType destType = Context.getPointerType(destPointee);
4860 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004861 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004862 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004863 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004864 return destType;
4865 }
4866 return QualType();
4867}
4868
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004869/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004870/// ParenRange in parentheses.
4871static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004872 const PartialDiagnostic &Note,
4873 SourceRange ParenRange) {
4874 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4875 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4876 EndLoc.isValid()) {
4877 Self.Diag(Loc, Note)
4878 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4879 << FixItHint::CreateInsertion(EndLoc, ")");
4880 } else {
4881 // We can't display the parentheses, so just show the bare note.
4882 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004883 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004884}
4885
4886static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4887 return Opc >= BO_Mul && Opc <= BO_Shr;
4888}
4889
Hans Wennborg2f072b42011-06-09 17:06:51 +00004890/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4891/// expression, either using a built-in or overloaded operator,
4892/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
4893static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
4894 Expr **RHS) {
4895 E = E->IgnoreParenImpCasts();
4896 E = E->IgnoreConversionOperator();
4897 E = E->IgnoreParenImpCasts();
4898
4899 // Built-in binary operator.
4900 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4901 if (IsArithmeticOp(OP->getOpcode())) {
4902 *Opcode = OP->getOpcode();
4903 *RHS = OP->getRHS();
4904 return true;
4905 }
4906 }
4907
4908 // Overloaded operator.
4909 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4910 if (Call->getNumArgs() != 2)
4911 return false;
4912
4913 // Make sure this is really a binary operator that is safe to pass into
4914 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4915 OverloadedOperatorKind OO = Call->getOperator();
4916 if (OO < OO_Plus || OO > OO_Arrow)
4917 return false;
4918
4919 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4920 if (IsArithmeticOp(OpKind)) {
4921 *Opcode = OpKind;
4922 *RHS = Call->getArg(1);
4923 return true;
4924 }
4925 }
4926
4927 return false;
4928}
4929
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004930static bool IsLogicOp(BinaryOperatorKind Opc) {
4931 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4932}
4933
Hans Wennborg2f072b42011-06-09 17:06:51 +00004934/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4935/// or is a logical expression such as (x==y) which has int type, but is
4936/// commonly interpreted as boolean.
4937static bool ExprLooksBoolean(Expr *E) {
4938 E = E->IgnoreParenImpCasts();
4939
4940 if (E->getType()->isBooleanType())
4941 return true;
4942 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4943 return IsLogicOp(OP->getOpcode());
4944 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4945 return OP->getOpcode() == UO_LNot;
4946
4947 return false;
4948}
4949
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004950/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4951/// and binary operator are mixed in a way that suggests the programmer assumed
4952/// the conditional operator has higher precedence, for example:
4953/// "int x = a + someBinaryCondition ? 1 : 2".
4954static void DiagnoseConditionalPrecedence(Sema &Self,
4955 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004956 Expr *Condition,
4957 Expr *LHS,
4958 Expr *RHS) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00004959 BinaryOperatorKind CondOpcode;
4960 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004961
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004962 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00004963 return;
4964 if (!ExprLooksBoolean(CondRHS))
4965 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004966
Hans Wennborg2f072b42011-06-09 17:06:51 +00004967 // The condition is an arithmetic binary expression, with a right-
4968 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004969
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004970 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004971 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00004972 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004973
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004974 SuggestParentheses(Self, OpLoc,
4975 Self.PDiag(diag::note_precedence_conditional_silence)
4976 << BinaryOperator::getOpcodeStr(CondOpcode),
4977 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00004978
4979 SuggestParentheses(Self, OpLoc,
4980 Self.PDiag(diag::note_precedence_conditional_first),
4981 SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004982}
4983
Steve Narofff69936d2007-09-16 03:34:24 +00004984/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004985/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00004986ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00004987 SourceLocation ColonLoc,
4988 Expr *CondExpr, Expr *LHSExpr,
4989 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00004990 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4991 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00004992 OpaqueValueExpr *opaqueValue = 0;
4993 Expr *commonExpr = 0;
4994 if (LHSExpr == 0) {
4995 commonExpr = CondExpr;
4996
4997 // We usually want to apply unary conversions *before* saving, except
4998 // in the special case of a C++ l-value conditional.
4999 if (!(getLangOptions().CPlusPlus
5000 && !commonExpr->isTypeDependent()
5001 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5002 && commonExpr->isGLValue()
5003 && commonExpr->isOrdinaryOrBitFieldObject()
5004 && RHSExpr->isOrdinaryOrBitFieldObject()
5005 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005006 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5007 if (commonRes.isInvalid())
5008 return ExprError();
5009 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005010 }
5011
5012 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5013 commonExpr->getType(),
5014 commonExpr->getValueKind(),
5015 commonExpr->getObjectKind());
5016 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005017 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005018
John McCallf89e55a2010-11-18 06:31:45 +00005019 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005020 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005021 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5022 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005023 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005024 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5025 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005026 return ExprError();
5027
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005028 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5029 RHS.get());
5030
John McCall56ca35d2011-02-17 10:25:35 +00005031 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005032 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5033 LHS.take(), ColonLoc,
5034 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005035
5036 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005037 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005038 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5039 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005040}
5041
John McCalle4be87e2011-01-31 23:13:11 +00005042// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005043// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005044// routine is it effectively iqnores the qualifiers on the top level pointee.
5045// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5046// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005047static Sema::AssignConvertType
5048checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5049 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5050 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005051
Reid Spencer5f016e22007-07-11 17:01:13 +00005052 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005053 const Type *lhptee, *rhptee;
5054 Qualifiers lhq, rhq;
5055 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5056 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005057
John McCalle4be87e2011-01-31 23:13:11 +00005058 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005059
5060 // C99 6.5.16.1p1: This following citation is common to constraints
5061 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5062 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005063 Qualifiers lq;
5064
John McCallf85e1932011-06-15 23:02:42 +00005065 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5066 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5067 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5068 // Ignore lifetime for further calculation.
5069 lhq.removeObjCLifetime();
5070 rhq.removeObjCLifetime();
5071 }
5072
John McCall86c05f32011-02-01 00:10:29 +00005073 if (!lhq.compatiblyIncludes(rhq)) {
5074 // Treat address-space mismatches as fatal. TODO: address subspaces
5075 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5076 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5077
John McCallf85e1932011-06-15 23:02:42 +00005078 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005079 // and from void*.
John McCallf85e1932011-06-15 23:02:42 +00005080 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5081 .compatiblyIncludes(
5082 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall22348732011-03-26 02:56:45 +00005083 && (lhptee->isVoidType() || rhptee->isVoidType()))
5084 ; // keep old
5085
John McCallf85e1932011-06-15 23:02:42 +00005086 // Treat lifetime mismatches as fatal.
5087 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5088 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5089
John McCall86c05f32011-02-01 00:10:29 +00005090 // For GCC compatibility, other qualifier mismatches are treated
5091 // as still compatible in C.
5092 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5093 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005094
Mike Stumpeed9cac2009-02-19 03:04:26 +00005095 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5096 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005097 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005098 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005099 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005100 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005101
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005102 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005103 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005104 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005105 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005106
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005107 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005108 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005109 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005110
5111 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005112 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005113 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005114 }
John McCall86c05f32011-02-01 00:10:29 +00005115
Mike Stumpeed9cac2009-02-19 03:04:26 +00005116 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005117 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005118 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5119 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005120 // Check if the pointee types are compatible ignoring the sign.
5121 // We explicitly check for char so that we catch "char" vs
5122 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005123 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005124 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005125 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005126 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005127
Chris Lattner6a2b9262009-10-17 20:33:28 +00005128 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005129 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005130 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005131 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005132
John McCall86c05f32011-02-01 00:10:29 +00005133 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005134 // Types are compatible ignoring the sign. Qualifier incompatibility
5135 // takes priority over sign incompatibility because the sign
5136 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005137 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005138 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005139
John McCalle4be87e2011-01-31 23:13:11 +00005140 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005141 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005142
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005143 // If we are a multi-level pointer, it's possible that our issue is simply
5144 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5145 // the eventual target type is the same and the pointers have the same
5146 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005147 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005148 do {
John McCall86c05f32011-02-01 00:10:29 +00005149 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5150 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005151 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005152
John McCall86c05f32011-02-01 00:10:29 +00005153 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005154 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005155 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005156
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005157 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005158 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005159 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005160 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005161}
5162
John McCalle4be87e2011-01-31 23:13:11 +00005163/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005164/// block pointer types are compatible or whether a block and normal pointer
5165/// are compatible. It is more restrict than comparing two function pointer
5166// types.
John McCalle4be87e2011-01-31 23:13:11 +00005167static Sema::AssignConvertType
5168checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5169 QualType rhsType) {
5170 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5171 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5172
Steve Naroff1c7d0672008-09-04 15:10:53 +00005173 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005174
Steve Naroff1c7d0672008-09-04 15:10:53 +00005175 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCalle4be87e2011-01-31 23:13:11 +00005176 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5177 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005178
John McCalle4be87e2011-01-31 23:13:11 +00005179 // In C++, the types have to match exactly.
5180 if (S.getLangOptions().CPlusPlus)
5181 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005182
John McCalle4be87e2011-01-31 23:13:11 +00005183 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005184
Steve Naroff1c7d0672008-09-04 15:10:53 +00005185 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005186 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5187 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005188
John McCalle4be87e2011-01-31 23:13:11 +00005189 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5190 return Sema::IncompatibleBlockPointer;
5191
Steve Naroff1c7d0672008-09-04 15:10:53 +00005192 return ConvTy;
5193}
5194
John McCalle4be87e2011-01-31 23:13:11 +00005195/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005196/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005197static Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005198checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType,
5199 QualType rhsType) {
John McCalle4be87e2011-01-31 23:13:11 +00005200 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5201 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5202
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005203 if (lhsType->isObjCBuiltinType()) {
5204 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005205 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5206 !rhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005207 return Sema::IncompatiblePointer;
5208 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005209 }
5210 if (rhsType->isObjCBuiltinType()) {
5211 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005212 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5213 !lhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005214 return Sema::IncompatiblePointer;
5215 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005216 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005217 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005218 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005219 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005220 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005221
John McCalle4be87e2011-01-31 23:13:11 +00005222 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5223 return Sema::CompatiblePointerDiscardsQualifiers;
5224
5225 if (S.Context.typesAreCompatible(lhsType, rhsType))
5226 return Sema::Compatible;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005227 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005228 return Sema::IncompatibleObjCQualifiedId;
5229 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005230}
5231
John McCall1c23e912010-11-16 02:32:08 +00005232Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005233Sema::CheckAssignmentConstraints(SourceLocation Loc,
5234 QualType lhsType, QualType rhsType) {
John McCall1c23e912010-11-16 02:32:08 +00005235 // Fake up an opaque expression. We don't actually care about what
5236 // cast operations are required, so if CheckAssignmentConstraints
5237 // adds casts to this they'll be wasted, but fortunately that doesn't
5238 // usually happen on valid code.
Douglas Gregorb608b982011-01-28 02:26:04 +00005239 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005240 ExprResult rhsPtr = &rhs;
John McCall1c23e912010-11-16 02:32:08 +00005241 CastKind K = CK_Invalid;
5242
5243 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5244}
5245
Mike Stumpeed9cac2009-02-19 03:04:26 +00005246/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5247/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005248/// pointers. Here are some objectionable examples that GCC considers warnings:
5249///
5250/// int a, *pint;
5251/// short *pshort;
5252/// struct foo *pfoo;
5253///
5254/// pint = pshort; // warning: assignment from incompatible pointer type
5255/// a = pint; // warning: assignment makes integer from pointer without a cast
5256/// pint = a; // warning: assignment makes pointer from integer without a cast
5257/// pint = pfoo; // warning: assignment from incompatible pointer type
5258///
5259/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005260/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005261///
John McCalldaa8e4e2010-11-15 09:13:47 +00005262/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005263Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00005264Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCalldaa8e4e2010-11-15 09:13:47 +00005265 CastKind &Kind) {
John Wiegley429bb272011-04-08 18:41:53 +00005266 QualType rhsType = rhs.get()->getType();
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005267 QualType origLhsType = lhsType;
John McCall1c23e912010-11-16 02:32:08 +00005268
Chris Lattnerfc144e22008-01-04 23:18:45 +00005269 // Get canonical types. We're not formatting these types, just comparing
5270 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00005271 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5272 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005273
John McCallb6cfa242011-01-31 22:28:28 +00005274 // Common case: no conversion required.
John McCalldaa8e4e2010-11-15 09:13:47 +00005275 if (lhsType == rhsType) {
5276 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005277 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005278 }
5279
Douglas Gregor9d293df2008-10-28 00:22:11 +00005280 // If the left-hand side is a reference type, then we are in a
5281 // (rare!) case where we've allowed the use of references in C,
5282 // e.g., as a parameter type in a built-in function. In this case,
5283 // just make sure that the type referenced is compatible with the
5284 // right-hand side type. The caller is responsible for adjusting
5285 // lhsType so that the resulting expression does not have reference
5286 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005287 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005288 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5289 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005290 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005291 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005292 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005293 }
John McCallb6cfa242011-01-31 22:28:28 +00005294
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005295 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5296 // to the same ExtVector type.
5297 if (lhsType->isExtVectorType()) {
5298 if (rhsType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005299 return Incompatible;
5300 if (rhsType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005301 // CK_VectorSplat does T -> vector T, so first cast to the
5302 // element type.
5303 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5304 if (elType != rhsType) {
5305 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley429bb272011-04-08 18:41:53 +00005306 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005307 }
5308 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005309 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005310 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005311 }
Mike Stump1eb44332009-09-09 15:08:12 +00005312
John McCallb6cfa242011-01-31 22:28:28 +00005313 // Conversions to or from vector type.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005314 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00005315 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005316 // Allow assignments of an AltiVec vector type to an equivalent GCC
5317 // vector type and vice versa
5318 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5319 Kind = CK_BitCast;
5320 return Compatible;
5321 }
5322
Douglas Gregor255210e2010-08-06 10:14:59 +00005323 // If we are allowing lax vector conversions, and LHS and RHS are both
5324 // vectors, the total size only needs to be the same. This is a bitcast;
5325 // no bits are changed but the result type is different.
5326 if (getLangOptions().LaxVectorConversions &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005327 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005328 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005329 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005330 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005331 }
5332 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005333 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005334
John McCallb6cfa242011-01-31 22:28:28 +00005335 // Arithmetic conversions.
Douglas Gregor88623ad2010-05-23 21:53:47 +00005336 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005337 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall1c23e912010-11-16 02:32:08 +00005338 Kind = PrepareScalarCast(*this, rhs, lhsType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005339 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005340 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005341
John McCallb6cfa242011-01-31 22:28:28 +00005342 // Conversions to normal pointers.
5343 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5344 // U* -> T*
John McCalldaa8e4e2010-11-15 09:13:47 +00005345 if (isa<PointerType>(rhsType)) {
5346 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00005347 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005348 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005349
John McCallb6cfa242011-01-31 22:28:28 +00005350 // int -> T*
5351 if (rhsType->isIntegerType()) {
5352 Kind = CK_IntegralToPointer; // FIXME: null?
5353 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005354 }
John McCallb6cfa242011-01-31 22:28:28 +00005355
5356 // C pointers are not compatible with ObjC object pointers,
5357 // with two exceptions:
5358 if (isa<ObjCObjectPointerType>(rhsType)) {
5359 // - conversions to void*
5360 if (lhsPointer->getPointeeType()->isVoidType()) {
5361 Kind = CK_AnyPointerToObjCPointerCast;
5362 return Compatible;
5363 }
5364
5365 // - conversions from 'Class' to the redefinition type
5366 if (rhsType->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005367 Context.hasSameType(lhsType,
5368 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005369 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005370 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005371 }
Steve Naroffb4406862008-09-29 18:10:17 +00005372
John McCallb6cfa242011-01-31 22:28:28 +00005373 Kind = CK_BitCast;
5374 return IncompatiblePointer;
5375 }
5376
5377 // U^ -> void*
5378 if (rhsType->getAs<BlockPointerType>()) {
5379 if (lhsPointer->getPointeeType()->isVoidType()) {
5380 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005381 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005382 }
Steve Naroffb4406862008-09-29 18:10:17 +00005383 }
John McCallb6cfa242011-01-31 22:28:28 +00005384
Steve Naroff1c7d0672008-09-04 15:10:53 +00005385 return Incompatible;
5386 }
5387
John McCallb6cfa242011-01-31 22:28:28 +00005388 // Conversions to block pointers.
Steve Naroff1c7d0672008-09-04 15:10:53 +00005389 if (isa<BlockPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005390 // U^ -> T^
5391 if (rhsType->isBlockPointerType()) {
5392 Kind = CK_AnyPointerToBlockPointerCast;
John McCalle4be87e2011-01-31 23:13:11 +00005393 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00005394 }
5395
5396 // int or null -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00005397 if (rhsType->isIntegerType()) {
5398 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005399 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005400 }
5401
John McCallb6cfa242011-01-31 22:28:28 +00005402 // id -> T^
5403 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5404 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005405 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005406 }
Steve Naroffb4406862008-09-29 18:10:17 +00005407
John McCallb6cfa242011-01-31 22:28:28 +00005408 // void* -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00005409 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005410 if (RHSPT->getPointeeType()->isVoidType()) {
5411 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005412 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005413 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005414
Chris Lattnerfc144e22008-01-04 23:18:45 +00005415 return Incompatible;
5416 }
5417
John McCallb6cfa242011-01-31 22:28:28 +00005418 // Conversions to Objective-C pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00005419 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005420 // A* -> B*
5421 if (rhsType->isObjCObjectPointerType()) {
5422 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005423 Sema::AssignConvertType result =
5424 checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
5425 if (getLangOptions().ObjCAutoRefCount &&
5426 result == Compatible &&
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005427 !CheckObjCARCUnavailableWeakConversion(origLhsType, rhsType))
5428 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005429 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005430 }
5431
5432 // int or null -> A*
John McCalldaa8e4e2010-11-15 09:13:47 +00005433 if (rhsType->isIntegerType()) {
5434 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005435 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005436 }
5437
John McCallb6cfa242011-01-31 22:28:28 +00005438 // In general, C pointers are not compatible with ObjC object pointers,
5439 // with two exceptions:
Steve Naroff14108da2009-07-10 23:34:53 +00005440 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005441 // - conversions from 'void*'
5442 if (rhsType->isVoidPointerType()) {
5443 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005444 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005445 }
5446
5447 // - conversions to 'Class' from its redefinition type
5448 if (lhsType->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005449 Context.hasSameType(rhsType,
5450 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005451 Kind = CK_BitCast;
5452 return Compatible;
5453 }
5454
5455 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005456 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005457 }
John McCallb6cfa242011-01-31 22:28:28 +00005458
5459 // T^ -> A*
5460 if (rhsType->isBlockPointerType()) {
5461 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005462 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005463 }
5464
Steve Naroff14108da2009-07-10 23:34:53 +00005465 return Incompatible;
5466 }
John McCallb6cfa242011-01-31 22:28:28 +00005467
5468 // Conversions from pointers that are not covered by the above.
Chris Lattner78eca282008-04-07 06:49:41 +00005469 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005470 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00005471 if (lhsType == Context.BoolTy) {
5472 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005473 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005474 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005475
John McCallb6cfa242011-01-31 22:28:28 +00005476 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00005477 if (lhsType->isIntegerType()) {
5478 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005479 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005480 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005481
Chris Lattnerfc144e22008-01-04 23:18:45 +00005482 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005483 }
John McCallb6cfa242011-01-31 22:28:28 +00005484
5485 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff14108da2009-07-10 23:34:53 +00005486 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005487 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00005488 if (lhsType == Context.BoolTy) {
5489 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005490 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005491 }
Steve Naroff14108da2009-07-10 23:34:53 +00005492
John McCallb6cfa242011-01-31 22:28:28 +00005493 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00005494 if (lhsType->isIntegerType()) {
5495 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005496 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005497 }
5498
Steve Naroff14108da2009-07-10 23:34:53 +00005499 return Incompatible;
5500 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005501
John McCallb6cfa242011-01-31 22:28:28 +00005502 // struct A -> struct B
Chris Lattnerfc144e22008-01-04 23:18:45 +00005503 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005504 if (Context.typesAreCompatible(lhsType, rhsType)) {
5505 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005506 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005507 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005508 }
John McCallb6cfa242011-01-31 22:28:28 +00005509
Reid Spencer5f016e22007-07-11 17:01:13 +00005510 return Incompatible;
5511}
5512
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005513/// \brief Constructs a transparent union from an expression that is
5514/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005515static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5516 ExprResult &EResult, QualType UnionType,
5517 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005518 // Build an initializer list that designates the appropriate member
5519 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005520 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005521 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00005522 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005523 SourceLocation());
5524 Initializer->setType(UnionType);
5525 Initializer->setInitializedFieldInUnion(Field);
5526
5527 // Build a compound literal constructing a value of the transparent
5528 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005529 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005530 EResult = S.Owned(
5531 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5532 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005533}
5534
5535Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005536Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5537 ExprResult &rExpr) {
John Wiegley429bb272011-04-08 18:41:53 +00005538 QualType FromType = rExpr.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005539
Mike Stump1eb44332009-09-09 15:08:12 +00005540 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005541 // transparent_union GCC extension.
5542 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005543 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005544 return Incompatible;
5545
5546 // The field to initialize within the transparent union.
5547 RecordDecl *UD = UT->getDecl();
5548 FieldDecl *InitField = 0;
5549 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005550 for (RecordDecl::field_iterator it = UD->field_begin(),
5551 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005552 it != itend; ++it) {
5553 if (it->getType()->isPointerType()) {
5554 // If the transparent union contains a pointer type, we allow:
5555 // 1) void pointer
5556 // 2) null pointer constant
5557 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005558 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005559 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005560 InitField = *it;
5561 break;
5562 }
Mike Stump1eb44332009-09-09 15:08:12 +00005563
John Wiegley429bb272011-04-08 18:41:53 +00005564 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005565 Expr::NPC_ValueDependentIsNull)) {
Richard Trieu67e29332011-08-02 04:35:43 +00005566 rExpr = ImpCastExprToType(rExpr.take(), it->getType(),
5567 CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005568 InitField = *it;
5569 break;
5570 }
5571 }
5572
John McCalldaa8e4e2010-11-15 09:13:47 +00005573 CastKind Kind = CK_Invalid;
John Wiegley429bb272011-04-08 18:41:53 +00005574 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005575 == Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +00005576 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005577 InitField = *it;
5578 break;
5579 }
5580 }
5581
5582 if (!InitField)
5583 return Incompatible;
5584
John Wiegley429bb272011-04-08 18:41:53 +00005585 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005586 return Compatible;
5587}
5588
Chris Lattner5cf216b2008-01-04 18:04:52 +00005589Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00005590Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005591 if (getLangOptions().CPlusPlus) {
5592 if (!lhsType->isRecordType()) {
5593 // C++ 5.17p3: If the left operand is not of class type, the
5594 // expression is implicitly converted (C++ 4) to the
5595 // cv-unqualified type of the left operand.
John Wiegley429bb272011-04-08 18:41:53 +00005596 ExprResult Res = PerformImplicitConversion(rExpr.get(),
5597 lhsType.getUnqualifiedType(),
5598 AA_Assigning);
5599 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005600 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005601 Sema::AssignConvertType result = Compatible;
5602 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieu67e29332011-08-02 04:35:43 +00005603 !CheckObjCARCUnavailableWeakConversion(lhsType,
5604 rExpr.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005605 result = IncompatibleObjCWeakRef;
John Wiegley429bb272011-04-08 18:41:53 +00005606 rExpr = move(Res);
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005607 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005608 }
5609
5610 // FIXME: Currently, we fall through and treat C++ classes like C
5611 // structures.
John McCallf6a16482010-12-04 03:47:34 +00005612 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005613
Steve Naroff529a4ad2007-11-27 17:58:44 +00005614 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5615 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00005616 if ((lhsType->isPointerType() ||
5617 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00005618 lhsType->isBlockPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00005619 && rExpr.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00005620 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00005621 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005622 return Compatible;
5623 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005624
Chris Lattner943140e2007-10-16 02:55:40 +00005625 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005626 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005627 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005628 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005629 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005630 // Suppress this for references: C++ 8.5.3p5.
John Wiegley429bb272011-04-08 18:41:53 +00005631 if (!lhsType->isReferenceType()) {
5632 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
5633 if (rExpr.isInvalid())
5634 return Incompatible;
5635 }
Steve Narofff1120de2007-08-24 22:33:52 +00005636
John McCalldaa8e4e2010-11-15 09:13:47 +00005637 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005638 Sema::AssignConvertType result =
John McCall1c23e912010-11-16 02:32:08 +00005639 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005640
Steve Narofff1120de2007-08-24 22:33:52 +00005641 // C99 6.5.16.1p2: The value of the right operand is converted to the
5642 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00005643 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5644 // so that we can use references in built-in functions even in C.
5645 // The getNonReferenceType() call makes sure that the resulting expression
5646 // does not have reference type.
John Wiegley429bb272011-04-08 18:41:53 +00005647 if (result != Incompatible && rExpr.get()->getType() != lhsType)
Richard Trieu67e29332011-08-02 04:35:43 +00005648 rExpr = ImpCastExprToType(rExpr.take(),
5649 lhsType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00005650 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00005651}
5652
Richard Trieu67e29332011-08-02 04:35:43 +00005653QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex,
5654 ExprResult &rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005655 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley429bb272011-04-08 18:41:53 +00005656 << lex.get()->getType() << rex.get()->getType()
5657 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00005658 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005659}
5660
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005661QualType Sema::CheckVectorOperands(ExprResult &lex, ExprResult &rex,
5662 SourceLocation Loc, bool isCompAssign) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00005663 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005664 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00005665 QualType lhsType =
John Wiegley429bb272011-04-08 18:41:53 +00005666 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattnerb77792e2008-07-26 22:17:49 +00005667 QualType rhsType =
John Wiegley429bb272011-04-08 18:41:53 +00005668 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005669
Nate Begemanbe2341d2008-07-14 18:02:46 +00005670 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005671 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00005672 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00005673
Douglas Gregor255210e2010-08-06 10:14:59 +00005674 // Handle the case of equivalent AltiVec and GCC vector types
5675 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5676 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005677 if (lhsType->isExtVectorType()) {
5678 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5679 return lhsType;
5680 }
5681
5682 if (!isCompAssign)
5683 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor255210e2010-08-06 10:14:59 +00005684 return rhsType;
5685 }
5686
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005687 if (getLangOptions().LaxVectorConversions &&
5688 Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) {
5689 // If we are allowing lax vector conversions, and LHS and RHS are both
5690 // vectors, the total size only needs to be the same. This is a
5691 // bitcast; no bits are changed but the result type is different.
5692 // FIXME: Should we really be allowing this?
5693 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5694 return lhsType;
5695 }
5696
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005697 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5698 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5699 bool swapped = false;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005700 if (rhsType->isExtVectorType() && !isCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005701 swapped = true;
5702 std::swap(rex, lex);
5703 std::swap(rhsType, lhsType);
5704 }
Mike Stump1eb44332009-09-09 15:08:12 +00005705
Nate Begemandde25982009-06-28 19:12:57 +00005706 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00005707 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005708 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005709 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005710 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5711 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00005712 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005713 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00005714 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005715 if (swapped) std::swap(rex, lex);
5716 return lhsType;
5717 }
5718 }
5719 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5720 rhsType->isRealFloatingType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005721 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5722 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00005723 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005724 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00005725 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005726 if (swapped) std::swap(rex, lex);
5727 return lhsType;
5728 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00005729 }
5730 }
Mike Stump1eb44332009-09-09 15:08:12 +00005731
Nate Begemandde25982009-06-28 19:12:57 +00005732 // Vectors of different size or scalar and non-ext-vector are errors.
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005733 if (swapped) std::swap(rex, lex);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005734 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley429bb272011-04-08 18:41:53 +00005735 << lex.get()->getType() << rex.get()->getType()
5736 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005737 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00005738}
5739
Richard Trieu67e29332011-08-02 04:35:43 +00005740QualType Sema::CheckMultiplyDivideOperands(ExprResult &lex, ExprResult &rex,
5741 SourceLocation Loc,
5742 bool isCompAssign, bool isDiv) {
5743 if (lex.get()->getType()->isVectorType() ||
5744 rex.get()->getType()->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005745 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005746
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005747 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00005748 if (lex.isInvalid() || rex.isInvalid())
5749 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005750
John Wiegley429bb272011-04-08 18:41:53 +00005751 if (!lex.get()->getType()->isArithmeticType() ||
5752 !rex.get()->getType()->isArithmeticType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00005753 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005754
Chris Lattner7ef655a2010-01-12 21:23:57 +00005755 // Check for division by zero.
5756 if (isDiv &&
Richard Trieu67e29332011-08-02 04:35:43 +00005757 rex.get()->isNullPointerConstant(Context,
5758 Expr::NPC_ValueDependentIsNotNull))
John Wiegley429bb272011-04-08 18:41:53 +00005759 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
Richard Trieu67e29332011-08-02 04:35:43 +00005760 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005761
Chris Lattner7ef655a2010-01-12 21:23:57 +00005762 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005763}
5764
Chris Lattner7ef655a2010-01-12 21:23:57 +00005765QualType Sema::CheckRemainderOperands(
John Wiegley429bb272011-04-08 18:41:53 +00005766 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
Richard Trieu67e29332011-08-02 04:35:43 +00005767 if (lex.get()->getType()->isVectorType() ||
5768 rex.get()->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005769 if (lex.get()->getType()->hasIntegerRepresentation() &&
5770 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005771 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Daniel Dunbar523aa602009-01-05 22:55:36 +00005772 return InvalidOperands(Loc, lex, rex);
5773 }
Steve Naroff90045e82007-07-13 23:32:42 +00005774
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005775 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00005776 if (lex.isInvalid() || rex.isInvalid())
5777 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005778
Richard Trieu67e29332011-08-02 04:35:43 +00005779 if (!lex.get()->getType()->isIntegerType() ||
5780 !rex.get()->getType()->isIntegerType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00005781 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005782
Chris Lattner7ef655a2010-01-12 21:23:57 +00005783 // Check for remainder by zero.
Richard Trieu67e29332011-08-02 04:35:43 +00005784 if (rex.get()->isNullPointerConstant(Context,
5785 Expr::NPC_ValueDependentIsNotNull))
John Wiegley429bb272011-04-08 18:41:53 +00005786 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
5787 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005788
Chris Lattner7ef655a2010-01-12 21:23:57 +00005789 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005790}
5791
Chandler Carruth13b21be2011-06-27 08:02:19 +00005792/// \brief Diagnose invalid arithmetic on two void pointers.
5793static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
5794 Expr *LHS, Expr *RHS) {
5795 S.Diag(Loc, S.getLangOptions().CPlusPlus
5796 ? diag::err_typecheck_pointer_arith_void_type
5797 : diag::ext_gnu_void_ptr)
5798 << 1 /* two pointers */ << LHS->getSourceRange() << RHS->getSourceRange();
5799}
5800
5801/// \brief Diagnose invalid arithmetic on a void pointer.
5802static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5803 Expr *Pointer) {
5804 S.Diag(Loc, S.getLangOptions().CPlusPlus
5805 ? diag::err_typecheck_pointer_arith_void_type
5806 : diag::ext_gnu_void_ptr)
5807 << 0 /* one pointer */ << Pointer->getSourceRange();
5808}
5809
5810/// \brief Diagnose invalid arithmetic on two function pointers.
5811static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5812 Expr *LHS, Expr *RHS) {
5813 assert(LHS->getType()->isAnyPointerType());
5814 assert(RHS->getType()->isAnyPointerType());
5815 S.Diag(Loc, S.getLangOptions().CPlusPlus
5816 ? diag::err_typecheck_pointer_arith_function_type
5817 : diag::ext_gnu_ptr_func_arith)
5818 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5819 // We only show the second type if it differs from the first.
5820 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5821 RHS->getType())
5822 << RHS->getType()->getPointeeType()
5823 << LHS->getSourceRange() << RHS->getSourceRange();
5824}
5825
5826/// \brief Diagnose invalid arithmetic on a function pointer.
5827static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5828 Expr *Pointer) {
5829 assert(Pointer->getType()->isAnyPointerType());
5830 S.Diag(Loc, S.getLangOptions().CPlusPlus
5831 ? diag::err_typecheck_pointer_arith_function_type
5832 : diag::ext_gnu_ptr_func_arith)
5833 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5834 << 0 /* one pointer, so only one type */
5835 << Pointer->getSourceRange();
5836}
5837
Richard Trieu097ecd22011-09-02 02:15:37 +00005838/// \brief Warn if Operand is incomplete pointer type
5839///
5840/// \returns True if pointer has incomplete type
5841static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
5842 Expr *Operand) {
5843 if ((Operand->getType()->isPointerType() &&
5844 !Operand->getType()->isDependentType()) ||
5845 Operand->getType()->isObjCObjectPointerType()) {
5846 QualType PointeeTy = Operand->getType()->getPointeeType();
5847 if (S.RequireCompleteType(
5848 Loc, PointeeTy,
5849 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5850 << PointeeTy << Operand->getSourceRange()))
5851 return true;
5852 }
5853 return false;
5854}
5855
Chandler Carruth13b21be2011-06-27 08:02:19 +00005856/// \brief Check the validity of an arithmetic pointer operand.
5857///
5858/// If the operand has pointer type, this code will check for pointer types
5859/// which are invalid in arithmetic operations. These will be diagnosed
5860/// appropriately, including whether or not the use is supported as an
5861/// extension.
5862///
5863/// \returns True when the operand is valid to use (even if as an extension).
5864static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5865 Expr *Operand) {
5866 if (!Operand->getType()->isAnyPointerType()) return true;
5867
5868 QualType PointeeTy = Operand->getType()->getPointeeType();
5869 if (PointeeTy->isVoidType()) {
5870 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5871 return !S.getLangOptions().CPlusPlus;
5872 }
5873 if (PointeeTy->isFunctionType()) {
5874 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5875 return !S.getLangOptions().CPlusPlus;
5876 }
5877
Richard Trieu097ecd22011-09-02 02:15:37 +00005878 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00005879
5880 return true;
5881}
5882
5883/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5884/// operands.
5885///
5886/// This routine will diagnose any invalid arithmetic on pointer operands much
5887/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5888/// for emitting a single diagnostic even for operations where both LHS and RHS
5889/// are (potentially problematic) pointers.
5890///
5891/// \returns True when the operand is valid to use (even if as an extension).
5892static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
5893 Expr *LHS, Expr *RHS) {
5894 bool isLHSPointer = LHS->getType()->isAnyPointerType();
5895 bool isRHSPointer = RHS->getType()->isAnyPointerType();
5896 if (!isLHSPointer && !isRHSPointer) return true;
5897
5898 QualType LHSPointeeTy, RHSPointeeTy;
5899 if (isLHSPointer) LHSPointeeTy = LHS->getType()->getPointeeType();
5900 if (isRHSPointer) RHSPointeeTy = RHS->getType()->getPointeeType();
5901
5902 // Check for arithmetic on pointers to incomplete types.
5903 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5904 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
5905 if (isLHSVoidPtr || isRHSVoidPtr) {
5906 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHS);
5907 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHS);
5908 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHS, RHS);
5909
5910 return !S.getLangOptions().CPlusPlus;
5911 }
5912
5913 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
5914 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
5915 if (isLHSFuncPtr || isRHSFuncPtr) {
5916 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHS);
5917 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, RHS);
5918 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS, RHS);
5919
5920 return !S.getLangOptions().CPlusPlus;
5921 }
5922
Richard Trieu097ecd22011-09-02 02:15:37 +00005923 if (checkArithmeticIncompletePointerType(S, Loc, LHS)) return false;
5924 if (checkArithmeticIncompletePointerType(S, Loc, RHS)) return false;
5925
Chandler Carruth13b21be2011-06-27 08:02:19 +00005926 return true;
5927}
5928
Richard Trieudb44a6b2011-09-01 22:53:23 +00005929/// \brief Check bad cases where we step over interface counts.
5930static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
5931 SourceLocation OpLoc,
5932 Expr *Op) {
5933 assert(Op->getType()->isAnyPointerType());
5934 QualType PointeeTy = Op->getType()->getPointeeType();
5935 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
5936 return true;
5937
5938 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5939 << PointeeTy << Op->getSourceRange();
5940 return false;
5941}
5942
5943/// \brief Warn when two pointers are incompatible.
5944static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
5945 Expr *LHS, Expr *RHS) {
5946 assert(LHS->getType()->isAnyPointerType());
5947 assert(RHS->getType()->isAnyPointerType());
5948 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5949 << LHS->getType() << RHS->getType() << LHS->getSourceRange()
5950 << RHS->getSourceRange();
5951}
5952
Chris Lattner7ef655a2010-01-12 21:23:57 +00005953QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00005954 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieu67e29332011-08-02 04:35:43 +00005955 if (lex.get()->getType()->isVectorType() ||
5956 rex.get()->getType()->isVectorType()) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005957 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00005958 if (CompLHSTy) *CompLHSTy = compType;
5959 return compType;
5960 }
Steve Naroff49b45262007-07-13 16:58:59 +00005961
Eli Friedmanab3a8522009-03-28 01:22:36 +00005962 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00005963 if (lex.isInvalid() || rex.isInvalid())
5964 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00005965
Reid Spencer5f016e22007-07-11 17:01:13 +00005966 // handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00005967 if (lex.get()->getType()->isArithmeticType() &&
5968 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005969 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005970 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005971 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005972
Eli Friedmand72d16e2008-05-18 18:08:51 +00005973 // Put any potential pointer into PExp
John Wiegley429bb272011-04-08 18:41:53 +00005974 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005975 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00005976 std::swap(PExp, IExp);
5977
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005978 if (PExp->getType()->isAnyPointerType()) {
Eli Friedmand72d16e2008-05-18 18:08:51 +00005979 if (IExp->getType()->isIntegerType()) {
Chandler Carruth13b21be2011-06-27 08:02:19 +00005980 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
5981 return QualType();
5982
Chris Lattnerb5f15622009-04-24 23:50:08 +00005983 // Diagnose bad cases where we step over interface counts.
Richard Trieudb44a6b2011-09-01 22:53:23 +00005984 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
Chris Lattnerb5f15622009-04-24 23:50:08 +00005985 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005986
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005987 // Check array bounds for pointer arithemtic
5988 CheckArrayAccess(PExp, IExp);
5989
Eli Friedmanab3a8522009-03-28 01:22:36 +00005990 if (CompLHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00005991 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman04e83572009-08-20 04:21:42 +00005992 if (LHSTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +00005993 LHSTy = lex.get()->getType();
Eli Friedman04e83572009-08-20 04:21:42 +00005994 if (LHSTy->isPromotableIntegerType())
5995 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005996 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00005997 *CompLHSTy = LHSTy;
5998 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00005999 return PExp->getType();
6000 }
6001 }
6002
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006003 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006004}
6005
Chris Lattnereca7be62008-04-07 05:30:13 +00006006// C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00006007QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Richard Trieu67e29332011-08-02 04:35:43 +00006008 SourceLocation Loc,
6009 QualType* CompLHSTy) {
6010 if (lex.get()->getType()->isVectorType() ||
6011 rex.get()->getType()->isVectorType()) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006012 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006013 if (CompLHSTy) *CompLHSTy = compType;
6014 return compType;
6015 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006016
Eli Friedmanab3a8522009-03-28 01:22:36 +00006017 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00006018 if (lex.isInvalid() || rex.isInvalid())
6019 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006020
Chris Lattner6e4ab612007-12-09 21:53:25 +00006021 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006022
Chris Lattner6e4ab612007-12-09 21:53:25 +00006023 // Handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00006024 if (lex.get()->getType()->isArithmeticType() &&
6025 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006026 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006027 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006028 }
Mike Stump1eb44332009-09-09 15:08:12 +00006029
Chris Lattner6e4ab612007-12-09 21:53:25 +00006030 // Either ptr - int or ptr - ptr.
John Wiegley429bb272011-04-08 18:41:53 +00006031 if (lex.get()->getType()->isAnyPointerType()) {
6032 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006033
Chris Lattnerb5f15622009-04-24 23:50:08 +00006034 // Diagnose bad cases where we step over interface counts.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006035 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, lex.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006036 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006037
Chris Lattner6e4ab612007-12-09 21:53:25 +00006038 // The result type of a pointer-int computation is the pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00006039 if (rex.get()->getType()->isIntegerType()) {
Chandler Carruth13b21be2011-06-27 08:02:19 +00006040 if (!checkArithmeticOpPointerOperand(*this, Loc, lex.get()))
6041 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006042
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006043 Expr *IExpr = rex.get()->IgnoreParenCasts();
6044 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6045 OK_Ordinary, IExpr->getExprLoc());
6046 // Check array bounds for pointer arithemtic
6047 CheckArrayAccess(lex.get()->IgnoreParenCasts(), &negRex);
6048
John Wiegley429bb272011-04-08 18:41:53 +00006049 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
6050 return lex.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006051 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006052
Chris Lattner6e4ab612007-12-09 21:53:25 +00006053 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006054 if (const PointerType *RHSPTy
6055 = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006056 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006057
Eli Friedman88d936b2009-05-16 13:54:38 +00006058 if (getLangOptions().CPlusPlus) {
6059 // Pointee types must be the same: C++ [expr.add]
6060 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudb44a6b2011-09-01 22:53:23 +00006061 diagnosePointerIncompatibility(*this, Loc, lex.get(), rex.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006062 }
6063 } else {
6064 // Pointee types must be compatible C99 6.5.6p3
6065 if (!Context.typesAreCompatible(
6066 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6067 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudb44a6b2011-09-01 22:53:23 +00006068 diagnosePointerIncompatibility(*this, Loc, lex.get(), rex.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006069 return QualType();
6070 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006071 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006072
Chandler Carruth13b21be2011-06-27 08:02:19 +00006073 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6074 lex.get(), rex.get()))
6075 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006076
John Wiegley429bb272011-04-08 18:41:53 +00006077 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006078 return Context.getPointerDiffType();
6079 }
6080 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006081
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006082 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006083}
6084
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006085static bool isScopedEnumerationType(QualType T) {
6086 if (const EnumType *ET = dyn_cast<EnumType>(T))
6087 return ET->getDecl()->isScoped();
6088 return false;
6089}
6090
John Wiegley429bb272011-04-08 18:41:53 +00006091static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth21206d52011-02-23 23:34:11 +00006092 SourceLocation Loc, unsigned Opc,
6093 QualType LHSTy) {
6094 llvm::APSInt Right;
6095 // Check right/shifter operand
Richard Trieu67e29332011-08-02 04:35:43 +00006096 if (rex.get()->isValueDependent() ||
6097 !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006098 return;
6099
6100 if (Right.isNegative()) {
John Wiegley429bb272011-04-08 18:41:53 +00006101 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006102 S.PDiag(diag::warn_shift_negative)
John Wiegley429bb272011-04-08 18:41:53 +00006103 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006104 return;
6105 }
6106 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley429bb272011-04-08 18:41:53 +00006107 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006108 if (Right.uge(LeftBits)) {
John Wiegley429bb272011-04-08 18:41:53 +00006109 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006110 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley429bb272011-04-08 18:41:53 +00006111 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006112 return;
6113 }
6114 if (Opc != BO_Shl)
6115 return;
6116
6117 // When left shifting an ICE which is signed, we can check for overflow which
6118 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6119 // integers have defined behavior modulo one more than the maximum value
6120 // representable in the result type, so never warn for those.
6121 llvm::APSInt Left;
Richard Trieu67e29332011-08-02 04:35:43 +00006122 if (lex.get()->isValueDependent() ||
6123 !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth21206d52011-02-23 23:34:11 +00006124 LHSTy->hasUnsignedIntegerRepresentation())
6125 return;
6126 llvm::APInt ResultBits =
6127 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6128 if (LeftBits.uge(ResultBits))
6129 return;
6130 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6131 Result = Result.shl(Right);
6132
Ted Kremenekfa821382011-06-15 00:54:52 +00006133 // Print the bit representation of the signed integer as an unsigned
6134 // hexadecimal number.
6135 llvm::SmallString<40> HexResult;
6136 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6137
Chandler Carruth21206d52011-02-23 23:34:11 +00006138 // If we are only missing a sign bit, this is less likely to result in actual
6139 // bugs -- if the result is cast back to an unsigned type, it will have the
6140 // expected value. Thus we place this behind a different warning that can be
6141 // turned off separately if needed.
6142 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006143 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6144 << HexResult.str() << LHSTy
John Wiegley429bb272011-04-08 18:41:53 +00006145 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006146 return;
6147 }
6148
6149 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Ted Kremenekfa821382011-06-15 00:54:52 +00006150 << HexResult.str() << Result.getMinSignedBits() << LHSTy
Richard Trieu67e29332011-08-02 04:35:43 +00006151 << Left.getBitWidth() << lex.get()->getSourceRange()
6152 << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006153}
6154
Chris Lattnereca7be62008-04-07 05:30:13 +00006155// C99 6.5.7
Richard Trieu67e29332011-08-02 04:35:43 +00006156QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex,
6157 SourceLocation Loc, unsigned Opc,
6158 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00006159 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley429bb272011-04-08 18:41:53 +00006160 if (!lex.get()->getType()->hasIntegerRepresentation() ||
6161 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006162 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006163
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006164 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6165 // hasIntegerRepresentation() above instead of this.
John Wiegley429bb272011-04-08 18:41:53 +00006166 if (isScopedEnumerationType(lex.get()->getType()) ||
6167 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006168 return InvalidOperands(Loc, lex, rex);
6169 }
6170
Nate Begeman2207d792009-10-25 02:26:48 +00006171 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu67e29332011-08-02 04:35:43 +00006172 if (lex.get()->getType()->isVectorType() ||
6173 rex.get()->getType()->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006174 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006175
Chris Lattnerca5eede2007-12-12 05:47:28 +00006176 // Shifts don't perform usual arithmetic conversions, they just do integer
6177 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006178
John McCall1bc80af2010-12-16 19:28:59 +00006179 // For the LHS, do usual unary conversions, but then reset them away
6180 // if this is a compound assignment.
John Wiegley429bb272011-04-08 18:41:53 +00006181 ExprResult old_lex = lex;
6182 lex = UsualUnaryConversions(lex.take());
6183 if (lex.isInvalid())
6184 return QualType();
6185 QualType LHSTy = lex.get()->getType();
John McCall1bc80af2010-12-16 19:28:59 +00006186 if (isCompAssign) lex = old_lex;
6187
6188 // The RHS is simpler.
John Wiegley429bb272011-04-08 18:41:53 +00006189 rex = UsualUnaryConversions(rex.take());
6190 if (rex.isInvalid())
6191 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006192
Ryan Flynnd0439682009-08-07 16:20:20 +00006193 // Sanity-check shift operands
Chandler Carruth21206d52011-02-23 23:34:11 +00006194 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnd0439682009-08-07 16:20:20 +00006195
Chris Lattnerca5eede2007-12-12 05:47:28 +00006196 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00006197 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006198}
6199
Chandler Carruth99919472010-07-10 12:30:03 +00006200static bool IsWithinTemplateSpecialization(Decl *D) {
6201 if (DeclContext *DC = D->getDeclContext()) {
6202 if (isa<ClassTemplateSpecializationDecl>(DC))
6203 return true;
6204 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6205 return FD->isFunctionTemplateSpecialization();
6206 }
6207 return false;
6208}
6209
Richard Trieue648ac32011-09-02 03:48:46 +00006210/// If two different enums are compared, raise a warning.
6211static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &lex,
6212 ExprResult &rex) {
Richard Trieue648ac32011-09-02 03:48:46 +00006213 QualType LHSStrippedType = lex.get()->IgnoreParenImpCasts()->getType();
6214 QualType RHSStrippedType = rex.get()->IgnoreParenImpCasts()->getType();
6215
6216 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6217 if (!LHSEnumType)
6218 return;
6219 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6220 if (!RHSEnumType)
6221 return;
6222
6223 // Ignore anonymous enums.
6224 if (!LHSEnumType->getDecl()->getIdentifier())
6225 return;
6226 if (!RHSEnumType->getDecl()->getIdentifier())
6227 return;
6228
6229 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6230 return;
6231
6232 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6233 << LHSStrippedType << RHSStrippedType
6234 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6235}
6236
Richard Trieu7be1be02011-09-02 02:55:45 +00006237/// \brief Diagnose bad pointer comparisons.
6238static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
6239 ExprResult &lex, ExprResult &rex,
6240 bool isError) {
6241 S.Diag(Loc, isError ? diag::err_typecheck_comparison_of_distinct_pointers
6242 : diag::ext_typecheck_comparison_of_distinct_pointers)
6243 << lex.get()->getType() << rex.get()->getType()
6244 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6245}
6246
6247/// \brief Returns false if the pointers are converted to a composite type,
6248/// true otherwise.
6249static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu43dff1b2011-09-02 21:44:27 +00006250 ExprResult &lex, ExprResult &rex) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006251 // C++ [expr.rel]p2:
6252 // [...] Pointer conversions (4.10) and qualification
6253 // conversions (4.4) are performed on pointer operands (or on
6254 // a pointer operand and a null pointer constant) to bring
6255 // them to their composite pointer type. [...]
6256 //
6257 // C++ [expr.eq]p1 uses the same notion for (in)equality
6258 // comparisons of pointers.
6259
6260 // C++ [expr.eq]p2:
6261 // In addition, pointers to members can be compared, or a pointer to
6262 // member and a null pointer constant. Pointer to member conversions
6263 // (4.11) and qualification conversions (4.4) are performed to bring
6264 // them to a common type. If one operand is a null pointer constant,
6265 // the common type is the type of the other operand. Otherwise, the
6266 // common type is a pointer to member type similar (4.4) to the type
6267 // of one of the operands, with a cv-qualification signature (4.4)
6268 // that is the union of the cv-qualification signatures of the operand
6269 // types.
6270
6271 QualType lType = lex.get()->getType();
6272 QualType rType = rex.get()->getType();
6273 assert((lType->isPointerType() && rType->isPointerType()) ||
6274 (lType->isMemberPointerType() && rType->isMemberPointerType()));
6275
6276 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006277 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
6278 QualType T = S.FindCompositePointerType(Loc, lex, rex, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006279 if (T.isNull()) {
6280 diagnoseDistinctPointerComparison(S, Loc, lex, rex, /*isError*/true);
6281 return true;
6282 }
6283
6284 if (NonStandardCompositeType)
6285 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6286 << lType << rType << T << lex.get()->getSourceRange()
6287 << rex.get()->getSourceRange();
6288
6289 lex = S.ImpCastExprToType(lex.take(), T, CK_BitCast);
6290 rex = S.ImpCastExprToType(rex.take(), T, CK_BitCast);
6291 return false;
6292}
6293
6294static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
6295 ExprResult &lex,
6296 ExprResult &rex,
6297 bool isError) {
6298 S.Diag(Loc,isError ? diag::err_typecheck_comparison_of_fptr_to_void
6299 : diag::ext_typecheck_comparison_of_fptr_to_void)
6300 << lex.get()->getType() << rex.get()->getType()
6301 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6302}
6303
Douglas Gregor0c6db942009-05-04 06:07:12 +00006304// C99 6.5.8, C++ [expr.rel]
Richard Trieu67e29332011-08-02 04:35:43 +00006305QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex,
6306 SourceLocation Loc, unsigned OpaqueOpc,
6307 bool isRelational) {
John McCall2de56d12010-08-25 11:45:40 +00006308 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006309
Chris Lattner02dd4b12009-12-05 05:40:13 +00006310 // Handle vector comparisons separately.
Richard Trieu67e29332011-08-02 04:35:43 +00006311 if (lex.get()->getType()->isVectorType() ||
6312 rex.get()->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006313 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006314
John Wiegley429bb272011-04-08 18:41:53 +00006315 QualType lType = lex.get()->getType();
6316 QualType rType = rex.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00006317
John Wiegley429bb272011-04-08 18:41:53 +00006318 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
6319 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006320
Richard Trieue648ac32011-09-02 03:48:46 +00006321 checkEnumComparison(*this, Loc, lex, rex);
Chandler Carruth543cb652011-02-17 08:37:06 +00006322
Douglas Gregor8eee1192010-06-22 22:12:46 +00006323 if (!lType->hasFloatingRepresentation() &&
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006324 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley429bb272011-04-08 18:41:53 +00006325 !lex.get()->getLocStart().isMacroID() &&
6326 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006327 // For non-floating point types, check for self-comparisons of the form
6328 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6329 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006330 //
6331 // NOTE: Don't warn about comparison expressions resulting from macro
6332 // expansion. Also don't warn about comparisons which are only self
6333 // comparisons within a template specialization. The warnings should catch
6334 // obvious cases in the definition of the template anyways. The idea is to
6335 // warn when the typed comparison operator will always evaluate to the same
6336 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006337 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006338 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006339 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006340 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006341 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006342 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006343 << (Opc == BO_EQ
6344 || Opc == BO_LE
6345 || Opc == BO_GE));
Douglas Gregord64fdd02010-06-08 19:50:34 +00006346 } else if (lType->isArrayType() && rType->isArrayType() &&
6347 !DRL->getDecl()->getType()->isReferenceType() &&
6348 !DRR->getDecl()->getType()->isReferenceType()) {
6349 // what is it always going to eval to?
6350 char always_evals_to;
6351 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006352 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006353 always_evals_to = 0; // false
6354 break;
John McCall2de56d12010-08-25 11:45:40 +00006355 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006356 always_evals_to = 1; // true
6357 break;
6358 default:
6359 // best we can say is 'a constant'
6360 always_evals_to = 2; // e.g. array1 <= array2
6361 break;
6362 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006363 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006364 << 1 // array
6365 << always_evals_to);
6366 }
6367 }
Chandler Carruth99919472010-07-10 12:30:03 +00006368 }
Mike Stump1eb44332009-09-09 15:08:12 +00006369
Chris Lattner55660a72009-03-08 19:39:53 +00006370 if (isa<CastExpr>(LHSStripped))
6371 LHSStripped = LHSStripped->IgnoreParenCasts();
6372 if (isa<CastExpr>(RHSStripped))
6373 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006374
Chris Lattner55660a72009-03-08 19:39:53 +00006375 // Warn about comparisons against a string constant (unless the other
6376 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006377 Expr *literalString = 0;
6378 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006379 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006380 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006381 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006382 literalString = lex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006383 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006384 } else if ((isa<StringLiteral>(RHSStripped) ||
6385 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006386 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006387 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006388 literalString = rex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006389 literalStringStripped = RHSStripped;
6390 }
6391
6392 if (literalString) {
6393 std::string resultComparison;
6394 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006395 case BO_LT: resultComparison = ") < 0"; break;
6396 case BO_GT: resultComparison = ") > 0"; break;
6397 case BO_LE: resultComparison = ") <= 0"; break;
6398 case BO_GE: resultComparison = ") >= 0"; break;
6399 case BO_EQ: resultComparison = ") == 0"; break;
6400 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00006401 default: assert(false && "Invalid comparison operator");
6402 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006403
Ted Kremenek351ba912011-02-23 01:52:04 +00006404 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006405 PDiag(diag::warn_stringcompare)
6406 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006407 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006408 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006409 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006410
Douglas Gregord64fdd02010-06-08 19:50:34 +00006411 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieu67e29332011-08-02 04:35:43 +00006412 if (lex.get()->getType()->isArithmeticType() &&
6413 rex.get()->getType()->isArithmeticType()) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006414 UsualArithmeticConversions(lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00006415 if (lex.isInvalid() || rex.isInvalid())
6416 return QualType();
6417 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00006418 else {
John Wiegley429bb272011-04-08 18:41:53 +00006419 lex = UsualUnaryConversions(lex.take());
6420 if (lex.isInvalid())
6421 return QualType();
6422
6423 rex = UsualUnaryConversions(rex.take());
6424 if (rex.isInvalid())
6425 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006426 }
6427
John Wiegley429bb272011-04-08 18:41:53 +00006428 lType = lex.get()->getType();
6429 rType = rex.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006430
Douglas Gregor447b69e2008-11-19 03:25:36 +00006431 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00006432 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00006433
Chris Lattnera5937dd2007-08-26 01:18:55 +00006434 if (isRelational) {
6435 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006436 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006437 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006438 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006439 if (lType->hasFloatingRepresentation())
John Wiegley429bb272011-04-08 18:41:53 +00006440 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006441
Chris Lattnera5937dd2007-08-26 01:18:55 +00006442 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006443 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006444 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006445
John Wiegley429bb272011-04-08 18:41:53 +00006446 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006447 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00006448 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006449 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006450
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006451 // All of the following pointer-related warnings are GCC extensions, except
6452 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00006453 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00006454 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006455 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00006456 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006457 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006458
Douglas Gregor0c6db942009-05-04 06:07:12 +00006459 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00006460 if (LCanPointeeTy == RCanPointeeTy)
6461 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006462 if (!isRelational &&
6463 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6464 // Valid unless comparison between non-null pointer and function pointer
6465 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006466 // In a SFINAE context, we treat this as a hard error to maintain
6467 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006468 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6469 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006470 diagnoseFunctionPointerToVoidComparison(
6471 *this, Loc, lex, rex, /*isError*/ isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006472
6473 if (isSFINAEContext())
6474 return QualType();
6475
John Wiegley429bb272011-04-08 18:41:53 +00006476 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006477 return ResultTy;
6478 }
6479 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006480
Richard Trieu7be1be02011-09-02 02:55:45 +00006481 if (convertPointersToCompositeType(*this, Loc, lex, rex))
Douglas Gregor0c6db942009-05-04 06:07:12 +00006482 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00006483 else
6484 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00006485 }
Eli Friedman3075e762009-08-23 00:27:47 +00006486 // C99 6.5.9p2 and C99 6.5.8p2
6487 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6488 RCanPointeeTy.getUnqualifiedType())) {
6489 // Valid unless a relational comparison of function pointers
6490 if (isRelational && LCanPointeeTy->isFunctionType()) {
6491 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00006492 << lType << rType << lex.get()->getSourceRange()
6493 << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00006494 }
6495 } else if (!isRelational &&
6496 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6497 // Valid unless comparison between non-null pointer and function pointer
6498 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00006499 && !LHSIsNull && !RHSIsNull)
6500 diagnoseFunctionPointerToVoidComparison(*this, Loc, lex, rex,
6501 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00006502 } else {
6503 // Invalid
Richard Trieu7be1be02011-09-02 02:55:45 +00006504 diagnoseDistinctPointerComparison(*this, Loc, lex, rex, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00006505 }
John McCall34d6f932011-03-11 04:25:25 +00006506 if (LCanPointeeTy != RCanPointeeTy) {
6507 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006508 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006509 else
John Wiegley429bb272011-04-08 18:41:53 +00006510 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006511 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00006512 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00006513 }
Mike Stump1eb44332009-09-09 15:08:12 +00006514
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006515 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006516 // Comparison of nullptr_t with itself.
6517 if (lType->isNullPtrType() && rType->isNullPtrType())
6518 return ResultTy;
6519
Mike Stump1eb44332009-09-09 15:08:12 +00006520 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00006521 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00006522 if (RHSIsNull &&
Douglas Gregor17e37c72011-06-01 15:12:24 +00006523 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregor16cd4b72011-06-16 18:52:05 +00006524 (!isRelational &&
6525 (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
John Wiegley429bb272011-04-08 18:41:53 +00006526 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregor443c2122010-08-07 13:36:37 +00006527 lType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006528 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006529 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006530 return ResultTy;
6531 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006532 if (LHSIsNull &&
Douglas Gregor17e37c72011-06-01 15:12:24 +00006533 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregor16cd4b72011-06-16 18:52:05 +00006534 (!isRelational &&
6535 (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
John Wiegley429bb272011-04-08 18:41:53 +00006536 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregor443c2122010-08-07 13:36:37 +00006537 rType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006538 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006539 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006540 return ResultTy;
6541 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006542
6543 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00006544 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00006545 lType->isMemberPointerType() && rType->isMemberPointerType()) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006546 if (convertPointersToCompositeType(*this, Loc, lex, rex))
Douglas Gregor20b3e992009-08-24 17:42:35 +00006547 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00006548 else
6549 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00006550 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006551
6552 // Handle scoped enumeration types specifically, since they don't promote
6553 // to integers.
John Wiegley429bb272011-04-08 18:41:53 +00006554 if (lex.get()->getType()->isEnumeralType() &&
Richard Trieu67e29332011-08-02 04:35:43 +00006555 Context.hasSameUnqualifiedType(lex.get()->getType(),
6556 rex.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00006557 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006558 }
Mike Stump1eb44332009-09-09 15:08:12 +00006559
Steve Naroff1c7d0672008-09-04 15:10:53 +00006560 // Handle block pointer types.
Richard Trieu67e29332011-08-02 04:35:43 +00006561 if (!isRelational && lType->isBlockPointerType() &&
6562 rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006563 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6564 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006565
Steve Naroff1c7d0672008-09-04 15:10:53 +00006566 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00006567 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006568 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieu67e29332011-08-02 04:35:43 +00006569 << lType << rType << lex.get()->getSourceRange()
6570 << rex.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00006571 }
John Wiegley429bb272011-04-08 18:41:53 +00006572 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006573 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006574 }
John Wiegley429bb272011-04-08 18:41:53 +00006575
Steve Naroff59f53942008-09-28 01:11:11 +00006576 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00006577 if (!isRelational
6578 && ((lType->isBlockPointerType() && rType->isPointerType())
6579 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00006580 if (!LHSIsNull && !RHSIsNull) {
John McCall34d6f932011-03-11 04:25:25 +00006581 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006582 ->getPointeeType()->isVoidType())
John McCall34d6f932011-03-11 04:25:25 +00006583 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006584 ->getPointeeType()->isVoidType())))
6585 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieu67e29332011-08-02 04:35:43 +00006586 << lType << rType << lex.get()->getSourceRange()
6587 << rex.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00006588 }
John McCall34d6f932011-03-11 04:25:25 +00006589 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006590 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006591 else
John Wiegley429bb272011-04-08 18:41:53 +00006592 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006593 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00006594 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00006595
John McCall34d6f932011-03-11 04:25:25 +00006596 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
6597 const PointerType *LPT = lType->getAs<PointerType>();
6598 const PointerType *RPT = rType->getAs<PointerType>();
6599 if (LPT || RPT) {
6600 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6601 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006602
Steve Naroffa8069f12008-11-17 19:49:16 +00006603 if (!LPtrToVoid && !RPtrToVoid &&
6604 !Context.typesAreCompatible(lType, rType)) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006605 diagnoseDistinctPointerComparison(*this, Loc, lex, rex,
6606 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00006607 }
John McCall34d6f932011-03-11 04:25:25 +00006608 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006609 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006610 else
John Wiegley429bb272011-04-08 18:41:53 +00006611 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006612 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00006613 }
Steve Naroff14108da2009-07-10 23:34:53 +00006614 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006615 if (!Context.areComparableObjCPointerTypes(lType, rType))
Richard Trieu7be1be02011-09-02 02:55:45 +00006616 diagnoseDistinctPointerComparison(*this, Loc, lex, rex,
6617 /*isError*/false);
John McCall34d6f932011-03-11 04:25:25 +00006618 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006619 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006620 else
John Wiegley429bb272011-04-08 18:41:53 +00006621 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006622 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00006623 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00006624 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006625 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6626 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006627 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006628 bool isError = false;
6629 if ((LHSIsNull && lType->isIntegerType()) ||
6630 (RHSIsNull && rType->isIntegerType())) {
6631 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006632 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006633 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006634 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006635 else if (getLangOptions().CPlusPlus) {
6636 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6637 isError = true;
6638 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006639 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00006640
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006641 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006642 Diag(Loc, DiagID)
Richard Trieu67e29332011-08-02 04:35:43 +00006643 << lType << rType << lex.get()->getSourceRange()
6644 << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006645 if (isError)
6646 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00006647 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006648
6649 if (lType->isIntegerType())
John Wiegley429bb272011-04-08 18:41:53 +00006650 lex = ImpCastExprToType(lex.take(), rType,
John McCall404cd162010-11-13 01:35:44 +00006651 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006652 else
John Wiegley429bb272011-04-08 18:41:53 +00006653 rex = ImpCastExprToType(rex.take(), lType,
John McCall404cd162010-11-13 01:35:44 +00006654 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006655 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006656 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006657
Steve Naroff39218df2008-09-04 16:56:14 +00006658 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00006659 if (!isRelational && RHSIsNull
6660 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006661 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006662 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006663 }
Mike Stumpaf199f32009-05-07 18:43:07 +00006664 if (!isRelational && LHSIsNull
6665 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006666 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006667 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006668 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006669
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006670 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006671}
6672
Nate Begemanbe2341d2008-07-14 18:02:46 +00006673/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00006674/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006675/// like a scalar comparison, a vector comparison produces a vector of integer
6676/// types.
John Wiegley429bb272011-04-08 18:41:53 +00006677QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006678 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006679 bool isRelational) {
6680 // Check to make sure we're operating on vectors of the same type and width,
6681 // Allowing one side to be a scalar of element type.
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006682 QualType vType = CheckVectorOperands(lex, rex, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00006683 if (vType.isNull())
6684 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006685
John Wiegley429bb272011-04-08 18:41:53 +00006686 QualType lType = lex.get()->getType();
6687 QualType rType = rex.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006688
Anton Yartsev7870b132011-03-27 15:36:07 +00006689 // If AltiVec, the comparison results in a numeric type, i.e.
6690 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00006691 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00006692 return Context.getLogicalOperationType();
6693
Nate Begemanbe2341d2008-07-14 18:02:46 +00006694 // For non-floating point types, check for self-comparisons of the form
6695 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6696 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006697 if (!lType->hasFloatingRepresentation()) {
John Wiegley429bb272011-04-08 18:41:53 +00006698 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
6699 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006700 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00006701 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00006702 PDiag(diag::warn_comparison_always)
6703 << 0 // self-
6704 << 2 // "a constant"
6705 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00006706 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006707
Nate Begemanbe2341d2008-07-14 18:02:46 +00006708 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006709 if (!isRelational && lType->hasFloatingRepresentation()) {
6710 assert (rType->hasFloatingRepresentation());
John Wiegley429bb272011-04-08 18:41:53 +00006711 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00006712 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006713
Nate Begemanbe2341d2008-07-14 18:02:46 +00006714 // Return the type for the comparison, which is the same as vector type for
6715 // integer vectors, or an integer type of identical size and number of
6716 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00006717 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00006718 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006719
John McCall183700f2009-09-21 23:43:11 +00006720 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00006721 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00006722 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006723 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00006724 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00006725 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6726
Mike Stumpeed9cac2009-02-19 03:04:26 +00006727 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00006728 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00006729 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6730}
6731
Reid Spencer5f016e22007-07-11 17:01:13 +00006732inline QualType Sema::CheckBitwiseOperands(
John Wiegley429bb272011-04-08 18:41:53 +00006733 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
Richard Trieu67e29332011-08-02 04:35:43 +00006734 if (lex.get()->getType()->isVectorType() ||
6735 rex.get()->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006736 if (lex.get()->getType()->hasIntegerRepresentation() &&
6737 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006738 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00006739
6740 return InvalidOperands(Loc, lex, rex);
6741 }
Steve Naroff90045e82007-07-13 23:32:42 +00006742
John Wiegley429bb272011-04-08 18:41:53 +00006743 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
Richard Trieu67e29332011-08-02 04:35:43 +00006744 QualType compType = UsualArithmeticConversions(lexResult, rexResult,
6745 isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00006746 if (lexResult.isInvalid() || rexResult.isInvalid())
6747 return QualType();
6748 lex = lexResult.take();
6749 rex = rexResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006750
John Wiegley429bb272011-04-08 18:41:53 +00006751 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6752 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006753 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006754 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006755}
6756
6757inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley429bb272011-04-08 18:41:53 +00006758 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00006759
6760 // Diagnose cases where the user write a logical and/or but probably meant a
6761 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6762 // is a constant.
Richard Trieu67e29332011-08-02 04:35:43 +00006763 if (lex.get()->getType()->isIntegerType() &&
6764 !lex.get()->getType()->isBooleanType() &&
John Wiegley429bb272011-04-08 18:41:53 +00006765 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00006766 // Don't warn in macros or template instantiations.
6767 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00006768 // If the RHS can be constant folded, and if it constant folds to something
6769 // that isn't 0 or 1 (which indicate a potential logical operation that
6770 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00006771 // Parens on the RHS are ignored.
Chris Lattnerb7690b42010-07-24 01:10:11 +00006772 Expr::EvalResult Result;
Chandler Carruth0683a142011-05-31 05:41:42 +00006773 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6774 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
6775 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6776 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6777 << rex.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006778 << (Opc == BO_LAnd ? "&&" : "||");
6779 // Suggest replacing the logical operator with the bitwise version
6780 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6781 << (Opc == BO_LAnd ? "&" : "|")
6782 << FixItHint::CreateReplacement(SourceRange(
6783 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6784 getLangOptions())),
6785 Opc == BO_LAnd ? "&" : "|");
6786 if (Opc == BO_LAnd)
6787 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6788 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6789 << FixItHint::CreateRemoval(
6790 SourceRange(
6791 Lexer::getLocForEndOfToken(lex.get()->getLocEnd(),
6792 0, getSourceManager(),
6793 getLangOptions()),
6794 rex.get()->getLocEnd()));
6795 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00006796 }
Chris Lattner90a8f272010-07-13 19:41:32 +00006797
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006798 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00006799 lex = UsualUnaryConversions(lex.take());
6800 if (lex.isInvalid())
6801 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006802
John Wiegley429bb272011-04-08 18:41:53 +00006803 rex = UsualUnaryConversions(rex.take());
6804 if (rex.isInvalid())
6805 return QualType();
6806
Richard Trieu67e29332011-08-02 04:35:43 +00006807 if (!lex.get()->getType()->isScalarType() ||
6808 !rex.get()->getType()->isScalarType())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006809 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006810
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006811 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00006812 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006813
John McCall75f7c0f2010-06-04 00:29:51 +00006814 // The following is safe because we only use this method for
6815 // non-overloadable operands.
6816
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006817 // C++ [expr.log.and]p1
6818 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00006819 // The operands are both contextually converted to type bool.
John Wiegley429bb272011-04-08 18:41:53 +00006820 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
6821 if (lexRes.isInvalid())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006822 return InvalidOperands(Loc, lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00006823 lex = move(lexRes);
6824
6825 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
6826 if (rexRes.isInvalid())
6827 return InvalidOperands(Loc, lex, rex);
6828 rex = move(rexRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006829
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006830 // C++ [expr.log.and]p2
6831 // C++ [expr.log.or]p2
6832 // The result is a bool.
6833 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006834}
6835
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006836/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6837/// is a read-only property; return true if so. A readonly property expression
6838/// depends on various declarations and thus must be treated specially.
6839///
Mike Stump1eb44332009-09-09 15:08:12 +00006840static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006841 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6842 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00006843 if (PropExpr->isImplicitProperty()) return false;
6844
6845 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6846 QualType BaseType = PropExpr->isSuperReceiver() ?
6847 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00006848 PropExpr->getBase()->getType();
6849
John McCall12f78a62010-12-02 01:19:52 +00006850 if (const ObjCObjectPointerType *OPT =
6851 BaseType->getAsObjCInterfacePointerType())
6852 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6853 if (S.isPropertyReadonly(PDecl, IFace))
6854 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006855 }
6856 return false;
6857}
6858
Fariborz Jahanian14086762011-03-28 23:47:18 +00006859static bool IsConstProperty(Expr *E, Sema &S) {
6860 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6861 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6862 if (PropExpr->isImplicitProperty()) return false;
6863
6864 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6865 QualType T = PDecl->getType();
6866 if (T->isReferenceType())
Fariborz Jahanian61750f22011-03-30 16:59:30 +00006867 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanian14086762011-03-28 23:47:18 +00006868 CanQualType CT = S.Context.getCanonicalType(T);
6869 return CT.isConstQualified();
6870 }
6871 return false;
6872}
6873
Fariborz Jahanian077f4902011-03-26 19:48:30 +00006874static bool IsReadonlyMessage(Expr *E, Sema &S) {
6875 if (E->getStmtClass() != Expr::MemberExprClass)
6876 return false;
6877 const MemberExpr *ME = cast<MemberExpr>(E);
6878 NamedDecl *Member = ME->getMemberDecl();
6879 if (isa<FieldDecl>(Member)) {
6880 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6881 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6882 return false;
6883 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6884 }
6885 return false;
6886}
6887
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006888/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6889/// emit an error and return true. If so, return false.
6890static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006891 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00006892 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006893 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006894 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6895 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian14086762011-03-28 23:47:18 +00006896 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6897 IsLV = Expr::MLV_Valid;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00006898 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6899 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006900 if (IsLV == Expr::MLV_Valid)
6901 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006902
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006903 unsigned Diag = 0;
6904 bool NeedType = false;
6905 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00006906 case Expr::MLV_ConstQualified:
6907 Diag = diag::err_typecheck_assign_const;
6908
John McCall7acddac2011-06-17 06:42:21 +00006909 // In ARC, use some specialized diagnostics for occasions where we
6910 // infer 'const'. These are always pseudo-strong variables.
John McCallf85e1932011-06-15 23:02:42 +00006911 if (S.getLangOptions().ObjCAutoRefCount) {
6912 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6913 if (declRef && isa<VarDecl>(declRef->getDecl())) {
6914 VarDecl *var = cast<VarDecl>(declRef->getDecl());
6915
John McCall7acddac2011-06-17 06:42:21 +00006916 // Use the normal diagnostic if it's pseudo-__strong but the
6917 // user actually wrote 'const'.
6918 if (var->isARCPseudoStrong() &&
6919 (!var->getTypeSourceInfo() ||
6920 !var->getTypeSourceInfo()->getType().isConstQualified())) {
6921 // There are two pseudo-strong cases:
6922 // - self
John McCallf85e1932011-06-15 23:02:42 +00006923 ObjCMethodDecl *method = S.getCurMethodDecl();
6924 if (method && var == method->getSelfDecl())
6925 Diag = diag::err_typecheck_arr_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00006926
6927 // - fast enumeration variables
6928 else
John McCallf85e1932011-06-15 23:02:42 +00006929 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00006930
John McCallf85e1932011-06-15 23:02:42 +00006931 SourceRange Assign;
6932 if (Loc != OrigLoc)
6933 Assign = SourceRange(OrigLoc, OrigLoc);
6934 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6935 // We need to preserve the AST regardless, so migration tool
6936 // can do its job.
6937 return false;
6938 }
6939 }
6940 }
6941
6942 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006943 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006944 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6945 NeedType = true;
6946 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006947 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006948 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6949 NeedType = true;
6950 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00006951 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006952 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6953 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00006954 case Expr::MLV_Valid:
6955 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00006956 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00006957 case Expr::MLV_MemberFunction:
6958 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006959 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6960 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006961 case Expr::MLV_IncompleteType:
6962 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00006963 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006964 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00006965 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00006966 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006967 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6968 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00006969 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006970 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6971 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00006972 case Expr::MLV_ReadonlyProperty:
6973 Diag = diag::error_readonly_property_assignment;
6974 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00006975 case Expr::MLV_NoSetterProperty:
6976 Diag = diag::error_nosetter_property_assignment;
6977 break;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00006978 case Expr::MLV_InvalidMessageExpression:
6979 Diag = diag::error_readonly_message_assignment;
6980 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00006981 case Expr::MLV_SubObjCPropertySetting:
6982 Diag = diag::error_no_subobject_property_setting;
6983 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006984 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00006985
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006986 SourceRange Assign;
6987 if (Loc != OrigLoc)
6988 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006989 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006990 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006991 else
Mike Stump1eb44332009-09-09 15:08:12 +00006992 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006993 return true;
6994}
6995
6996
6997
6998// C99 6.5.16.1
John Wiegley429bb272011-04-08 18:41:53 +00006999QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007000 SourceLocation Loc,
7001 QualType CompoundType) {
7002 // Verify that LHS is a modifiable lvalue, and emit error if not.
7003 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007004 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007005
7006 QualType LHSType = LHS->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007007 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7008 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007009 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007010 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007011 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007012 // Simple assignment "x = y".
John Wiegley429bb272011-04-08 18:41:53 +00007013 if (LHS->getObjectKind() == OK_ObjCProperty) {
7014 ExprResult LHSResult = Owned(LHS);
7015 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7016 if (LHSResult.isInvalid())
7017 return QualType();
7018 LHS = LHSResult.take();
7019 }
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007020 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007021 if (RHS.isInvalid())
7022 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007023 // Special case of NSObject attributes on c-style pointer types.
7024 if (ConvTy == IncompatiblePointer &&
7025 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007026 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007027 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007028 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007029 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007030
John McCallf89e55a2010-11-18 06:31:45 +00007031 if (ConvTy == Compatible &&
7032 getLangOptions().ObjCNonFragileABI &&
7033 LHSType->isObjCObjectType())
7034 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7035 << LHSType;
7036
Chris Lattner2c156472008-08-21 18:04:13 +00007037 // If the RHS is a unary plus or minus, check to see if they = and + are
7038 // right next to each other. If so, the user may have typo'd "x =+ 4"
7039 // instead of "x += 4".
John Wiegley429bb272011-04-08 18:41:53 +00007040 Expr *RHSCheck = RHS.get();
Chris Lattner2c156472008-08-21 18:04:13 +00007041 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7042 RHSCheck = ICE->getSubExpr();
7043 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007044 if ((UO->getOpcode() == UO_Plus ||
7045 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007046 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007047 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00007048 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7049 // And there is a space or other character before the subexpr of the
7050 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00007051 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7052 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007053 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007054 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007055 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007056 }
Chris Lattner2c156472008-08-21 18:04:13 +00007057 }
John McCallf85e1932011-06-15 23:02:42 +00007058
7059 if (ConvTy == Compatible) {
7060 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
7061 checkRetainCycles(LHS, RHS.get());
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007062 else if (getLangOptions().ObjCAutoRefCount)
7063 checkUnsafeExprAssigns(Loc, LHS, RHS.get());
John McCallf85e1932011-06-15 23:02:42 +00007064 }
Chris Lattner2c156472008-08-21 18:04:13 +00007065 } else {
7066 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007067 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007068 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007069
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007070 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007071 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007072 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007073
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +00007074 CheckForNullPointerDereference(*this, LHS);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007075
Reid Spencer5f016e22007-07-11 17:01:13 +00007076 // C99 6.5.16p3: The type of an assignment expression is the type of the
7077 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007078 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007079 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7080 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007081 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007082 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00007083 return (getLangOptions().CPlusPlus
7084 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007085}
7086
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007087// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007088static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007089 SourceLocation Loc) {
John Wiegley429bb272011-04-08 18:41:53 +00007090 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00007091
John McCallfb8721c2011-04-10 19:13:55 +00007092 LHS = S.CheckPlaceholderExpr(LHS.take());
7093 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007094 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007095 return QualType();
7096
John McCallcf2e5062010-10-12 07:14:40 +00007097 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7098 // operands, but not unary promotions.
7099 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007100
John McCallf6a16482010-12-04 03:47:34 +00007101 // So we treat the LHS as a ignored value, and in C++ we allow the
7102 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007103 LHS = S.IgnoredValueConversions(LHS.take());
7104 if (LHS.isInvalid())
7105 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007106
7107 if (!S.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007108 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7109 if (RHS.isInvalid())
7110 return QualType();
7111 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007112 S.RequireCompleteType(Loc, RHS.get()->getType(),
7113 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007114 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007115
John Wiegley429bb272011-04-08 18:41:53 +00007116 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007117}
7118
Steve Naroff49b45262007-07-13 16:58:59 +00007119/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7120/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007121static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7122 ExprValueKind &VK,
7123 SourceLocation OpLoc,
7124 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007125 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007126 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007127
Chris Lattner3528d352008-11-21 07:05:48 +00007128 QualType ResType = Op->getType();
7129 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007130
John McCall09431682010-11-18 19:01:18 +00007131 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007132 // Decrement of bool is not allowed.
7133 if (!isInc) {
John McCall09431682010-11-18 19:01:18 +00007134 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007135 return QualType();
7136 }
7137 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007138 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007139 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007140 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007141 } else if (ResType->isAnyPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007142 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007143 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007144 return QualType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00007145
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007146 // Diagnose bad cases where we step over interface counts.
Richard Trieudb44a6b2011-09-01 22:53:23 +00007147 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007148 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007149 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007150 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007151 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007152 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007153 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007154 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007155 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007156 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7157 isInc, isPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00007158 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7159 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007160 } else {
John McCall09431682010-11-18 19:01:18 +00007161 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00007162 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007163 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007164 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007165 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007166 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007167 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007168 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007169 // In C++, a prefix increment is the same type as the operand. Otherwise
7170 // (in C or with postfix), the increment is the unqualified type of the
7171 // operand.
John McCall09431682010-11-18 19:01:18 +00007172 if (isPrefix && S.getLangOptions().CPlusPlus) {
7173 VK = VK_LValue;
7174 return ResType;
7175 } else {
7176 VK = VK_RValue;
7177 return ResType.getUnqualifiedType();
7178 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007179}
7180
John Wiegley429bb272011-04-08 18:41:53 +00007181ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCallf6a16482010-12-04 03:47:34 +00007182 assert(E->getValueKind() == VK_LValue &&
7183 E->getObjectKind() == OK_ObjCProperty);
7184 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7185
Douglas Gregor926df6c2011-06-11 01:09:30 +00007186 QualType T = E->getType();
7187 QualType ReceiverType;
7188 if (PRE->isObjectReceiver())
7189 ReceiverType = PRE->getBase()->getType();
7190 else if (PRE->isSuperReceiver())
7191 ReceiverType = PRE->getSuperReceiverType();
7192 else
7193 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7194
John McCallf6a16482010-12-04 03:47:34 +00007195 ExprValueKind VK = VK_RValue;
7196 if (PRE->isImplicitProperty()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00007197 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007198 PRE->getImplicitPropertyGetter()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00007199 T = getMessageSendResultType(ReceiverType, GetterMethod,
7200 PRE->isClassReceiver(),
7201 PRE->isSuperReceiver());
7202 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007203 }
7204 else {
7205 Diag(PRE->getLocation(), diag::err_getter_not_found)
7206 << PRE->getBase()->getType();
7207 }
John McCallf6a16482010-12-04 03:47:34 +00007208 }
Douglas Gregor926df6c2011-06-11 01:09:30 +00007209
7210 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCallf6a16482010-12-04 03:47:34 +00007211 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00007212
7213 ExprResult Result = MaybeBindToTemporary(E);
7214 if (!Result.isInvalid())
7215 E = Result.take();
John Wiegley429bb272011-04-08 18:41:53 +00007216
7217 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00007218}
7219
Richard Trieu67e29332011-08-02 04:35:43 +00007220void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7221 QualType &LHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00007222 assert(LHS.get()->getValueKind() == VK_LValue &&
7223 LHS.get()->getObjectKind() == OK_ObjCProperty);
7224 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCallf6a16482010-12-04 03:47:34 +00007225
John McCallf85e1932011-06-15 23:02:42 +00007226 bool Consumed = false;
7227
John Wiegley429bb272011-04-08 18:41:53 +00007228 if (PropRef->isImplicitProperty()) {
John McCallf6a16482010-12-04 03:47:34 +00007229 // If using property-dot syntax notation for assignment, and there is a
7230 // setter, RHS expression is being passed to the setter argument. So,
7231 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley429bb272011-04-08 18:41:53 +00007232 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCallf6a16482010-12-04 03:47:34 +00007233 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7234 LHSTy = (*P)->getType();
John McCallf85e1932011-06-15 23:02:42 +00007235 Consumed = (getLangOptions().ObjCAutoRefCount &&
7236 (*P)->hasAttr<NSConsumedAttr>());
John McCallf6a16482010-12-04 03:47:34 +00007237
7238 // Otherwise, if the getter returns an l-value, just call that.
7239 } else {
John Wiegley429bb272011-04-08 18:41:53 +00007240 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCallf6a16482010-12-04 03:47:34 +00007241 ExprValueKind VK = Expr::getValueKindForType(Result);
7242 if (VK == VK_LValue) {
John Wiegley429bb272011-04-08 18:41:53 +00007243 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7244 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCallf6a16482010-12-04 03:47:34 +00007245 return;
John McCall12f78a62010-12-02 01:19:52 +00007246 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007247 }
John McCallf85e1932011-06-15 23:02:42 +00007248 } else if (getLangOptions().ObjCAutoRefCount) {
7249 const ObjCMethodDecl *setter
7250 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7251 if (setter) {
7252 ObjCMethodDecl::param_iterator P = setter->param_begin();
7253 LHSTy = (*P)->getType();
7254 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7255 }
John McCallf6a16482010-12-04 03:47:34 +00007256 }
7257
John McCallf85e1932011-06-15 23:02:42 +00007258 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7259 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007260 InitializedEntity Entity =
John McCallf85e1932011-06-15 23:02:42 +00007261 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley429bb272011-04-08 18:41:53 +00007262 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCallf85e1932011-06-15 23:02:42 +00007263 if (!ArgE.isInvalid()) {
John Wiegley429bb272011-04-08 18:41:53 +00007264 RHS = ArgE;
John McCallf85e1932011-06-15 23:02:42 +00007265 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7266 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7267 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007268 }
7269}
7270
7271
Anders Carlsson369dee42008-02-01 07:15:58 +00007272/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007273/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007274/// where the declaration is needed for type checking. We only need to
7275/// handle cases when the expression references a function designator
7276/// or is an lvalue. Here are some examples:
7277/// - &(x) => x
7278/// - &*****f => f for f a function designator.
7279/// - &s.xx => s
7280/// - &s.zz[1].yy -> s, if zz is an array
7281/// - *(x + 1) -> x, if x is an array
7282/// - &"123"[2] -> 0
7283/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007284static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007285 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007286 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007287 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007288 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007289 // If this is an arrow operator, the address is an offset from
7290 // the base's value, so the object the base refers to is
7291 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007292 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007293 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007294 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007295 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007296 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007297 // FIXME: This code shouldn't be necessary! We should catch the implicit
7298 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007299 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7300 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7301 if (ICE->getSubExpr()->getType()->isArrayType())
7302 return getPrimaryDecl(ICE->getSubExpr());
7303 }
7304 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007305 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007306 case Stmt::UnaryOperatorClass: {
7307 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007308
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007309 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007310 case UO_Real:
7311 case UO_Imag:
7312 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007313 return getPrimaryDecl(UO->getSubExpr());
7314 default:
7315 return 0;
7316 }
7317 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007318 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007319 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007320 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007321 // If the result of an implicit cast is an l-value, we care about
7322 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007323 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007324 default:
7325 return 0;
7326 }
7327}
7328
Richard Trieu09a26ad2011-09-02 00:47:55 +00007329/// \brief Diagnose invalid operand for address of operations.
7330///
7331/// \param Type The type of operand which cannot have its address taken.
7332/// 0:bit-field 1:vector element 2:property expression 3:register variable
7333static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7334 Expr *E, unsigned Type) {
7335 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7336}
7337
Reid Spencer5f016e22007-07-11 17:01:13 +00007338/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007339/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007340/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007341/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007342/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007343/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007344/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00007345static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7346 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00007347 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007348 return S.Context.DependentTy;
7349 if (OrigOp->getType() == S.Context.OverloadTy)
7350 return S.Context.OverloadTy;
John McCall755d8492011-04-12 00:42:48 +00007351 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7352 return S.Context.UnknownAnyTy;
John McCall864c0412011-04-26 20:42:42 +00007353 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7354 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7355 << OrigOp->getSourceRange();
7356 return QualType();
7357 }
John McCall9c72c602010-08-27 09:08:28 +00007358
John McCall755d8492011-04-12 00:42:48 +00007359 assert(!OrigOp->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00007360
John McCall9c72c602010-08-27 09:08:28 +00007361 // Make sure to ignore parentheses in subsequent checks
7362 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007363
John McCall09431682010-11-18 19:01:18 +00007364 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007365 // Implement C99-only parts of addressof rules.
7366 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007367 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007368 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7369 // (assuming the deref expression is valid).
7370 return uOp->getSubExpr()->getType();
7371 }
7372 // Technically, there should be a check for array subscript
7373 // expressions here, but the result of one is always an lvalue anyway.
7374 }
John McCall5808ce42011-02-03 08:15:49 +00007375 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007376 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007377
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007378 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007379 bool sfinae = S.isSFINAEContext();
7380 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7381 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007382 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007383 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007384 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007385 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007386 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007387 } else if (lval == Expr::LV_MemberFunction) {
7388 // If it's an instance method, make a member pointer.
7389 // The expression must have exactly the form &A::foo.
7390
7391 // If the underlying expression isn't a decl ref, give up.
7392 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007393 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007394 << OrigOp->getSourceRange();
7395 return QualType();
7396 }
7397 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7398 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7399
7400 // The id-expression was parenthesized.
7401 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00007402 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007403 << OrigOp->getSourceRange();
7404
7405 // The method was named without a qualifier.
7406 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007407 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007408 << op->getSourceRange();
7409 }
7410
John McCall09431682010-11-18 19:01:18 +00007411 return S.Context.getMemberPointerType(op->getType(),
7412 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007413 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007414 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007415 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007416 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00007417 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00007418 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00007419 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007420 return QualType();
7421 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007422 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007423 // The operand cannot be a bit-field
Richard Trieu09a26ad2011-09-02 00:47:55 +00007424 diagnoseAddressOfInvalidType(S, OpLoc, op, /*bit-field*/ 0);
7425 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007426 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007427 // The operand cannot be an element of a vector
Richard Trieu09a26ad2011-09-02 00:47:55 +00007428 diagnoseAddressOfInvalidType(S, OpLoc, op, /*vector element*/ 1);
Steve Naroffbcb2b612008-02-29 23:30:25 +00007429 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007430 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007431 // cannot take address of a property expression.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007432 diagnoseAddressOfInvalidType(S, OpLoc, op, /*property expression*/ 2);
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007433 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007434 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007435 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007436 // with the register storage-class specifier.
7437 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00007438 // in C++ it is not error to take address of a register
7439 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00007440 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00007441 !S.getLangOptions().CPlusPlus) {
Richard Trieu09a26ad2011-09-02 00:47:55 +00007442 diagnoseAddressOfInvalidType(S, OpLoc, op, /*register variable*/ 3);
Reid Spencer5f016e22007-07-11 17:01:13 +00007443 return QualType();
7444 }
John McCallba135432009-11-21 08:51:07 +00007445 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00007446 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00007447 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00007448 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00007449 // Could be a pointer to member, though, if there is an explicit
7450 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00007451 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00007452 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007453 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00007454 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00007455 S.Diag(OpLoc,
7456 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00007457 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007458 return QualType();
7459 }
Mike Stump1eb44332009-09-09 15:08:12 +00007460
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00007461 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7462 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00007463 return S.Context.getMemberPointerType(op->getType(),
7464 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007465 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00007466 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00007467 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00007468 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00007469 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00007470
Eli Friedman441cf102009-05-16 23:27:50 +00007471 if (lval == Expr::LV_IncompleteVoidType) {
7472 // Taking the address of a void variable is technically illegal, but we
7473 // allow it in cases which are otherwise valid.
7474 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00007475 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00007476 }
7477
Reid Spencer5f016e22007-07-11 17:01:13 +00007478 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00007479 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00007480 return S.Context.getObjCObjectPointerType(op->getType());
7481 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007482}
7483
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007484/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00007485static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7486 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00007487 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007488 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007489
John Wiegley429bb272011-04-08 18:41:53 +00007490 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7491 if (ConvResult.isInvalid())
7492 return QualType();
7493 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007494 QualType OpTy = Op->getType();
7495 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00007496
7497 if (isa<CXXReinterpretCastExpr>(Op)) {
7498 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7499 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7500 Op->getSourceRange());
7501 }
7502
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007503 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7504 // is an incomplete type or void. It would be possible to warn about
7505 // dereferencing a void pointer, but it's completely well-defined, and such a
7506 // warning is unlikely to catch any mistakes.
7507 if (const PointerType *PT = OpTy->getAs<PointerType>())
7508 Result = PT->getPointeeType();
7509 else if (const ObjCObjectPointerType *OPT =
7510 OpTy->getAs<ObjCObjectPointerType>())
7511 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00007512 else {
John McCallfb8721c2011-04-10 19:13:55 +00007513 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007514 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007515 if (PR.take() != Op)
7516 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007517 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007518
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007519 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00007520 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007521 << OpTy << Op->getSourceRange();
7522 return QualType();
7523 }
John McCall09431682010-11-18 19:01:18 +00007524
7525 // Dereferences are usually l-values...
7526 VK = VK_LValue;
7527
7528 // ...except that certain expressions are never l-values in C.
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00007529 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00007530 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007531
7532 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00007533}
7534
John McCall2de56d12010-08-25 11:45:40 +00007535static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007536 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007537 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007538 switch (Kind) {
7539 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00007540 case tok::periodstar: Opc = BO_PtrMemD; break;
7541 case tok::arrowstar: Opc = BO_PtrMemI; break;
7542 case tok::star: Opc = BO_Mul; break;
7543 case tok::slash: Opc = BO_Div; break;
7544 case tok::percent: Opc = BO_Rem; break;
7545 case tok::plus: Opc = BO_Add; break;
7546 case tok::minus: Opc = BO_Sub; break;
7547 case tok::lessless: Opc = BO_Shl; break;
7548 case tok::greatergreater: Opc = BO_Shr; break;
7549 case tok::lessequal: Opc = BO_LE; break;
7550 case tok::less: Opc = BO_LT; break;
7551 case tok::greaterequal: Opc = BO_GE; break;
7552 case tok::greater: Opc = BO_GT; break;
7553 case tok::exclaimequal: Opc = BO_NE; break;
7554 case tok::equalequal: Opc = BO_EQ; break;
7555 case tok::amp: Opc = BO_And; break;
7556 case tok::caret: Opc = BO_Xor; break;
7557 case tok::pipe: Opc = BO_Or; break;
7558 case tok::ampamp: Opc = BO_LAnd; break;
7559 case tok::pipepipe: Opc = BO_LOr; break;
7560 case tok::equal: Opc = BO_Assign; break;
7561 case tok::starequal: Opc = BO_MulAssign; break;
7562 case tok::slashequal: Opc = BO_DivAssign; break;
7563 case tok::percentequal: Opc = BO_RemAssign; break;
7564 case tok::plusequal: Opc = BO_AddAssign; break;
7565 case tok::minusequal: Opc = BO_SubAssign; break;
7566 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7567 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7568 case tok::ampequal: Opc = BO_AndAssign; break;
7569 case tok::caretequal: Opc = BO_XorAssign; break;
7570 case tok::pipeequal: Opc = BO_OrAssign; break;
7571 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007572 }
7573 return Opc;
7574}
7575
John McCall2de56d12010-08-25 11:45:40 +00007576static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007577 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007578 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007579 switch (Kind) {
7580 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00007581 case tok::plusplus: Opc = UO_PreInc; break;
7582 case tok::minusminus: Opc = UO_PreDec; break;
7583 case tok::amp: Opc = UO_AddrOf; break;
7584 case tok::star: Opc = UO_Deref; break;
7585 case tok::plus: Opc = UO_Plus; break;
7586 case tok::minus: Opc = UO_Minus; break;
7587 case tok::tilde: Opc = UO_Not; break;
7588 case tok::exclaim: Opc = UO_LNot; break;
7589 case tok::kw___real: Opc = UO_Real; break;
7590 case tok::kw___imag: Opc = UO_Imag; break;
7591 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007592 }
7593 return Opc;
7594}
7595
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007596/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7597/// This warning is only emitted for builtin assignment operations. It is also
7598/// suppressed in the event of macro expansions.
7599static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7600 SourceLocation OpLoc) {
7601 if (!S.ActiveTemplateInstantiations.empty())
7602 return;
7603 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7604 return;
7605 lhs = lhs->IgnoreParenImpCasts();
7606 rhs = rhs->IgnoreParenImpCasts();
7607 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7608 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7609 if (!LeftDeclRef || !RightDeclRef ||
7610 LeftDeclRef->getLocation().isMacroID() ||
7611 RightDeclRef->getLocation().isMacroID())
7612 return;
7613 const ValueDecl *LeftDecl =
7614 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7615 const ValueDecl *RightDecl =
7616 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7617 if (LeftDecl != RightDecl)
7618 return;
7619 if (LeftDecl->getType().isVolatileQualified())
7620 return;
7621 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7622 if (RefTy->getPointeeType().isVolatileQualified())
7623 return;
7624
7625 S.Diag(OpLoc, diag::warn_self_assignment)
7626 << LeftDeclRef->getType()
7627 << lhs->getSourceRange() << rhs->getSourceRange();
7628}
7629
Richard Trieue648ac32011-09-02 03:48:46 +00007630// checkArithmeticNull - Detect when a NULL constant is used improperly in an
7631// expression. These are mainly cases where the null pointer is used as an
7632// integer instead of a pointer.
7633static void checkArithmeticNull(Sema &S, ExprResult &lex, ExprResult &rex,
7634 SourceLocation Loc, bool isCompare) {
7635 // The canonical way to check for a GNU null is with isNullPointerConstant,
7636 // but we use a bit of a hack here for speed; this is a relatively
7637 // hot path, and isNullPointerConstant is slow.
7638 bool LeftNull = isa<GNUNullExpr>(lex.get()->IgnoreParenImpCasts());
7639 bool RightNull = isa<GNUNullExpr>(rex.get()->IgnoreParenImpCasts());
7640
7641 // Detect when a NULL constant is used improperly in an expression. These
7642 // are mainly cases where the null pointer is used as an integer instead
7643 // of a pointer.
7644 if (!LeftNull && !RightNull)
7645 return;
7646
7647 QualType LeftType = lex.get()->getType();
7648 QualType RightType = rex.get()->getType();
7649
7650 // Avoid analyzing cases where the result will either be invalid (and
7651 // diagnosed as such) or entirely valid and not something to warn about.
7652 if (LeftType->isBlockPointerType() || LeftType->isMemberPointerType() ||
7653 LeftType->isFunctionType() || RightType->isBlockPointerType() ||
7654 RightType->isMemberPointerType() || RightType->isFunctionType())
7655 return;
7656
7657 // Comparison operations would not make sense with a null pointer no matter
7658 // what the other expression is.
7659 if (!isCompare) {
7660 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
7661 << (LeftNull ? lex.get()->getSourceRange() : SourceRange())
7662 << (RightNull ? rex.get()->getSourceRange() : SourceRange());
7663 return;
7664 }
7665
7666 // The rest of the operations only make sense with a null pointer
7667 // if the other expression is a pointer.
7668 if (LeftNull == RightNull || LeftType->isAnyPointerType() ||
7669 LeftType->canDecayToPointerType() || RightType->isAnyPointerType() ||
7670 RightType->canDecayToPointerType())
7671 return;
7672
7673 S.Diag(Loc, diag::warn_null_in_comparison_operation)
7674 << LeftNull /* LHS is NULL */
7675 << (LeftNull ? rex.get()->getType() : lex.get()->getType())
7676 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7677}
Douglas Gregoreaebc752008-11-06 23:29:22 +00007678/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7679/// operator @p Opc at location @c TokLoc. This routine only supports
7680/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00007681ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007682 BinaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007683 Expr *lhsExpr, Expr *rhsExpr) {
7684 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007685 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00007686 // The following two variables are used for compound assignment operators
7687 QualType CompLHSTy; // Type of LHS after promotions for computation
7688 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00007689 ExprValueKind VK = VK_RValue;
7690 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00007691
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007692 // Check if a 'foo<int>' involved in a binary op, identifies a single
7693 // function unambiguously (i.e. an lvalue ala 13.4)
7694 // But since an assignment can trigger target based overload, exclude it in
7695 // our blind search. i.e:
7696 // template<class T> void f(); template<class T, class U> void f(U);
7697 // f<int> == 0; // resolve f<int> blindly
7698 // void (*p)(int); p = f<int>; // resolve f<int> using target
7699 if (Opc != BO_Assign) {
John McCallfb8721c2011-04-10 19:13:55 +00007700 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007701 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00007702 lhs = move(resolvedLHS);
John McCall1de4d4e2011-04-07 08:22:57 +00007703
John McCallfb8721c2011-04-10 19:13:55 +00007704 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007705 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00007706 rhs = move(resolvedRHS);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007707 }
7708
Richard Trieue648ac32011-09-02 03:48:46 +00007709 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
7710 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
7711 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
7712 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
7713 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
7714 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign)
7715 checkArithmeticNull(*this, lhs, rhs, OpLoc, /*isCompare=*/false);
7716 else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
7717 Opc == BO_EQ || Opc == BO_NE)
7718 checkArithmeticNull(*this, lhs, rhs, OpLoc, /*isCompare=*/true);
Richard Trieu3e95ba92011-06-16 21:36:56 +00007719
Douglas Gregoreaebc752008-11-06 23:29:22 +00007720 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007721 case BO_Assign:
John Wiegley429bb272011-04-08 18:41:53 +00007722 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00007723 if (getLangOptions().CPlusPlus &&
John Wiegley429bb272011-04-08 18:41:53 +00007724 lhs.get()->getObjectKind() != OK_ObjCProperty) {
7725 VK = lhs.get()->getValueKind();
7726 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007727 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007728 if (!ResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00007729 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007730 break;
John McCall2de56d12010-08-25 11:45:40 +00007731 case BO_PtrMemD:
7732 case BO_PtrMemI:
John McCallf89e55a2010-11-18 06:31:45 +00007733 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007734 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00007735 break;
John McCall2de56d12010-08-25 11:45:40 +00007736 case BO_Mul:
7737 case BO_Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007738 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00007739 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007740 break;
John McCall2de56d12010-08-25 11:45:40 +00007741 case BO_Rem:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007742 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7743 break;
John McCall2de56d12010-08-25 11:45:40 +00007744 case BO_Add:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007745 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7746 break;
John McCall2de56d12010-08-25 11:45:40 +00007747 case BO_Sub:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007748 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7749 break;
John McCall2de56d12010-08-25 11:45:40 +00007750 case BO_Shl:
7751 case BO_Shr:
Chandler Carruth21206d52011-02-23 23:34:11 +00007752 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007753 break;
John McCall2de56d12010-08-25 11:45:40 +00007754 case BO_LE:
7755 case BO_LT:
7756 case BO_GE:
7757 case BO_GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00007758 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007759 break;
John McCall2de56d12010-08-25 11:45:40 +00007760 case BO_EQ:
7761 case BO_NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00007762 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007763 break;
John McCall2de56d12010-08-25 11:45:40 +00007764 case BO_And:
7765 case BO_Xor:
7766 case BO_Or:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007767 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7768 break;
John McCall2de56d12010-08-25 11:45:40 +00007769 case BO_LAnd:
7770 case BO_LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00007771 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007772 break;
John McCall2de56d12010-08-25 11:45:40 +00007773 case BO_MulAssign:
7774 case BO_DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007775 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00007776 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007777 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007778 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7779 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007780 break;
John McCall2de56d12010-08-25 11:45:40 +00007781 case BO_RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007782 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7783 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007784 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7785 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007786 break;
John McCall2de56d12010-08-25 11:45:40 +00007787 case BO_AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007788 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00007789 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7790 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007791 break;
John McCall2de56d12010-08-25 11:45:40 +00007792 case BO_SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007793 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00007794 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7795 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007796 break;
John McCall2de56d12010-08-25 11:45:40 +00007797 case BO_ShlAssign:
7798 case BO_ShrAssign:
Chandler Carruth21206d52011-02-23 23:34:11 +00007799 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007800 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007801 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7802 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007803 break;
John McCall2de56d12010-08-25 11:45:40 +00007804 case BO_AndAssign:
7805 case BO_XorAssign:
7806 case BO_OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007807 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7808 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007809 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7810 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007811 break;
John McCall2de56d12010-08-25 11:45:40 +00007812 case BO_Comma:
John McCall09431682010-11-18 19:01:18 +00007813 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00007814 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
7815 VK = rhs.get()->getValueKind();
7816 OK = rhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007817 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00007818 break;
7819 }
John Wiegley429bb272011-04-08 18:41:53 +00007820 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00007821 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007822
7823 // Check for array bounds violations for both sides of the BinaryOperator
7824 CheckArrayAccess(lhs.get());
7825 CheckArrayAccess(rhs.get());
7826
Eli Friedmanab3a8522009-03-28 01:22:36 +00007827 if (CompResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00007828 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
7829 ResultTy, VK, OK, OpLoc));
Richard Trieu67e29332011-08-02 04:35:43 +00007830 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() !=
7831 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00007832 VK = VK_LValue;
John Wiegley429bb272011-04-08 18:41:53 +00007833 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007834 }
John Wiegley429bb272011-04-08 18:41:53 +00007835 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
7836 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00007837 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00007838}
7839
Sebastian Redlaee3c932009-10-27 12:10:02 +00007840/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7841/// operators are mixed in a way that suggests that the programmer forgot that
7842/// comparison operators have higher precedence. The most typical example of
7843/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00007844static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007845 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00007846 typedef BinaryOperator BinOp;
7847 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7848 rhsopc = static_cast<BinOp::Opcode>(-1);
7849 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007850 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00007851 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007852 rhsopc = BO->getOpcode();
7853
7854 // Subs are not binary operators.
7855 if (lhsopc == -1 && rhsopc == -1)
7856 return;
7857
7858 // Bitwise operations are sometimes used as eager logical ops.
7859 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00007860 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7861 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007862 return;
7863
Richard Trieu70979d42011-08-10 22:41:34 +00007864 bool isLeftComp = BinOp::isComparisonOp(lhsopc);
7865 bool isRightComp = BinOp::isComparisonOp(rhsopc);
7866 if (!isLeftComp && !isRightComp) return;
7867
7868 SourceRange DiagRange = isLeftComp ? SourceRange(lhs->getLocStart(), OpLoc)
7869 : SourceRange(OpLoc, rhs->getLocEnd());
7870 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(lhsopc)
7871 : BinOp::getOpcodeStr(rhsopc);
7872 SourceRange ParensRange = isLeftComp ?
7873 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(),
7874 rhs->getLocEnd())
7875 : SourceRange(lhs->getLocStart(),
7876 cast<BinOp>(rhs)->getLHS()->getLocStart());
7877
7878 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7879 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7880 SuggestParentheses(Self, OpLoc,
7881 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
7882 rhs->getSourceRange());
7883 SuggestParentheses(Self, OpLoc,
7884 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7885 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007886}
7887
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007888/// \brief It accepts a '&' expr that is inside a '|' one.
7889/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7890/// in parentheses.
7891static void
7892EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7893 BinaryOperator *Bop) {
7894 assert(Bop->getOpcode() == BO_And);
7895 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7896 << Bop->getSourceRange() << OpLoc;
7897 SuggestParentheses(Self, Bop->getOperatorLoc(),
7898 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7899 Bop->getSourceRange());
7900}
7901
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007902/// \brief It accepts a '&&' expr that is inside a '||' one.
7903/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7904/// in parentheses.
7905static void
7906EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00007907 BinaryOperator *Bop) {
7908 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007909 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7910 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00007911 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007912 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007913 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007914}
7915
7916/// \brief Returns true if the given expression can be evaluated as a constant
7917/// 'true'.
7918static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7919 bool Res;
7920 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7921}
7922
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007923/// \brief Returns true if the given expression can be evaluated as a constant
7924/// 'false'.
7925static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7926 bool Res;
7927 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7928}
7929
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007930/// \brief Look for '&&' in the left hand of a '||' expr.
7931static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007932 Expr *OrLHS, Expr *OrRHS) {
7933 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007934 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007935 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7936 if (EvaluatesAsFalse(S, OrRHS))
7937 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007938 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7939 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7940 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7941 } else if (Bop->getOpcode() == BO_LOr) {
7942 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7943 // If it's "a || b && 1 || c" we didn't warn earlier for
7944 // "a || b && 1", but warn now.
7945 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7946 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7947 }
7948 }
7949 }
7950}
7951
7952/// \brief Look for '&&' in the right hand of a '||' expr.
7953static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007954 Expr *OrLHS, Expr *OrRHS) {
7955 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007956 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007957 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7958 if (EvaluatesAsFalse(S, OrLHS))
7959 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007960 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7961 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7962 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007963 }
7964 }
7965}
7966
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007967/// \brief Look for '&' in the left or right hand of a '|' expr.
7968static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7969 Expr *OrArg) {
7970 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7971 if (Bop->getOpcode() == BO_And)
7972 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7973 }
7974}
7975
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007976/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007977/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00007978static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007979 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007980 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00007981 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007982 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7983
7984 // Diagnose "arg1 & arg2 | arg3"
7985 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7986 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, lhs);
7987 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, rhs);
7988 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007989
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007990 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7991 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00007992 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007993 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7994 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007995 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007996}
7997
Reid Spencer5f016e22007-07-11 17:01:13 +00007998// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00007999ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008000 tok::TokenKind Kind,
8001 Expr *lhs, Expr *rhs) {
8002 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Narofff69936d2007-09-16 03:34:24 +00008003 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8004 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008005
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008006 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8007 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8008
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008009 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8010}
8011
John McCall60d7b3a2010-08-24 06:29:42 +00008012ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008013 BinaryOperatorKind Opc,
8014 Expr *lhs, Expr *rhs) {
John McCall01b2e4e2010-12-06 05:26:58 +00008015 if (getLangOptions().CPlusPlus) {
8016 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008017
John McCall01b2e4e2010-12-06 05:26:58 +00008018 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8019 UseBuiltinOperator = false;
8020 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8021 UseBuiltinOperator = true;
8022 } else {
8023 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8024 !rhs->getType()->isOverloadableType();
8025 }
8026
8027 if (!UseBuiltinOperator) {
8028 // Find all of the overloaded operators visible from this
8029 // point. We perform both an operator-name lookup from the local
8030 // scope and an argument-dependent lookup based on the types of
8031 // the arguments.
8032 UnresolvedSet<16> Functions;
8033 OverloadedOperatorKind OverOp
8034 = BinaryOperator::getOverloadedOperator(Opc);
8035 if (S && OverOp != OO_None)
8036 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8037 Functions);
8038
8039 // Build the (potentially-overloaded, potentially-dependent)
8040 // binary operation.
8041 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8042 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008043 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008044
Douglas Gregoreaebc752008-11-06 23:29:22 +00008045 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008046 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00008047}
8048
John McCall60d7b3a2010-08-24 06:29:42 +00008049ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008050 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008051 Expr *InputExpr) {
8052 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008053 ExprValueKind VK = VK_RValue;
8054 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008055 QualType resultType;
8056 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008057 case UO_PreInc:
8058 case UO_PreDec:
8059 case UO_PostInc:
8060 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008061 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008062 Opc == UO_PreInc ||
8063 Opc == UO_PostInc,
8064 Opc == UO_PreInc ||
8065 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008066 break;
John McCall2de56d12010-08-25 11:45:40 +00008067 case UO_AddrOf:
John Wiegley429bb272011-04-08 18:41:53 +00008068 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008069 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008070 case UO_Deref: {
John McCallfb8721c2011-04-10 19:13:55 +00008071 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008072 if (!resolved.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008073 Input = move(resolved);
8074 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8075 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008076 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008077 }
John McCall2de56d12010-08-25 11:45:40 +00008078 case UO_Plus:
8079 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008080 Input = UsualUnaryConversions(Input.take());
8081 if (Input.isInvalid()) return ExprError();
8082 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008083 if (resultType->isDependentType())
8084 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008085 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8086 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008087 break;
8088 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8089 resultType->isEnumeralType())
8090 break;
8091 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008092 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008093 resultType->isPointerType())
8094 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008095 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008096 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008097 if (Input.isInvalid()) return ExprError();
8098 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008099 }
Douglas Gregor74253732008-11-19 15:42:04 +00008100
Sebastian Redl0eb23302009-01-19 00:08:26 +00008101 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008102 << resultType << Input.get()->getSourceRange());
8103
John McCall2de56d12010-08-25 11:45:40 +00008104 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008105 Input = UsualUnaryConversions(Input.take());
8106 if (Input.isInvalid()) return ExprError();
8107 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008108 if (resultType->isDependentType())
8109 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008110 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8111 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8112 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008113 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008114 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008115 else if (resultType->hasIntegerRepresentation())
8116 break;
8117 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008118 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008119 if (Input.isInvalid()) return ExprError();
8120 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008121 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008122 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008123 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008124 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008125 break;
John Wiegley429bb272011-04-08 18:41:53 +00008126
John McCall2de56d12010-08-25 11:45:40 +00008127 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008128 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008129 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8130 if (Input.isInvalid()) return ExprError();
8131 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008132 if (resultType->isDependentType())
8133 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008134 if (resultType->isScalarType()) {
8135 // C99 6.5.3.3p1: ok, fallthrough;
8136 if (Context.getLangOptions().CPlusPlus) {
8137 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8138 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008139 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8140 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008141 }
John McCall2cd11fe2010-10-12 02:09:17 +00008142 } else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008143 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008144 if (Input.isInvalid()) return ExprError();
8145 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008146 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008147 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008148 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008149 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008150
Reid Spencer5f016e22007-07-11 17:01:13 +00008151 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008152 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008153 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008154 break;
John McCall2de56d12010-08-25 11:45:40 +00008155 case UO_Real:
8156 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008157 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00008158 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley429bb272011-04-08 18:41:53 +00008159 if (Input.isInvalid()) return ExprError();
8160 if (Input.get()->getValueKind() != VK_RValue &&
8161 Input.get()->getObjectKind() == OK_Ordinary)
8162 VK = Input.get()->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00008163 break;
John McCall2de56d12010-08-25 11:45:40 +00008164 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008165 resultType = Input.get()->getType();
8166 VK = Input.get()->getValueKind();
8167 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008168 break;
8169 }
John Wiegley429bb272011-04-08 18:41:53 +00008170 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008171 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008172
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008173 // Check for array bounds violations in the operand of the UnaryOperator,
8174 // except for the '*' and '&' operators that have to be handled specially
8175 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8176 // that are explicitly defined as valid by the standard).
8177 if (Opc != UO_AddrOf && Opc != UO_Deref)
8178 CheckArrayAccess(Input.get());
8179
John Wiegley429bb272011-04-08 18:41:53 +00008180 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008181 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008182}
8183
John McCall60d7b3a2010-08-24 06:29:42 +00008184ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008185 UnaryOperatorKind Opc,
8186 Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00008187 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00008188 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008189 // Find all of the overloaded operators visible from this
8190 // point. We perform both an operator-name lookup from the local
8191 // scope and an argument-dependent lookup based on the types of
8192 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008193 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008194 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008195 if (S && OverOp != OO_None)
8196 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8197 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008198
John McCall9ae2f072010-08-23 23:25:46 +00008199 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008200 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008201
John McCall9ae2f072010-08-23 23:25:46 +00008202 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008203}
8204
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008205// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008206ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008207 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008208 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008209}
8210
Steve Naroff1b273c42007-09-16 14:56:35 +00008211/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008212ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008213 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008214 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008215 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008216 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008217 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008218}
8219
John McCallf85e1932011-06-15 23:02:42 +00008220/// Given the last statement in a statement-expression, check whether
8221/// the result is a producing expression (like a call to an
8222/// ns_returns_retained function) and, if so, rebuild it to hoist the
8223/// release out of the full-expression. Otherwise, return null.
8224/// Cannot fail.
8225static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
8226 // Should always be wrapped with one of these.
8227 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
8228 if (!cleanups) return 0;
8229
8230 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
8231 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
8232 return 0;
8233
8234 // Splice out the cast. This shouldn't modify any interesting
8235 // features of the statement.
8236 Expr *producer = cast->getSubExpr();
8237 assert(producer->getType() == cast->getType());
8238 assert(producer->getValueKind() == cast->getValueKind());
8239 cleanups->setSubExpr(producer);
8240 return cleanups;
8241}
8242
John McCall60d7b3a2010-08-24 06:29:42 +00008243ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008244Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008245 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008246 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8247 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8248
Douglas Gregordd8f5692010-03-10 04:54:39 +00008249 bool isFileScope
8250 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008251 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008252 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008253
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008254 // FIXME: there are a variety of strange constraints to enforce here, for
8255 // example, it is not possible to goto into a stmt expression apparently.
8256 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008257
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008258 // If there are sub stmts in the compound stmt, take the type of the last one
8259 // as the type of the stmtexpr.
8260 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008261 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008262 if (!Compound->body_empty()) {
8263 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008264 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008265 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008266 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8267 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008268 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008269 }
John McCallf85e1932011-06-15 23:02:42 +00008270
John Wiegley429bb272011-04-08 18:41:53 +00008271 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008272 // Do function/array conversion on the last expression, but not
8273 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00008274 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8275 if (LastExpr.isInvalid())
8276 return ExprError();
8277 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00008278
John Wiegley429bb272011-04-08 18:41:53 +00008279 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00008280 // In ARC, if the final expression ends in a consume, splice
8281 // the consume out and bind it later. In the alternate case
8282 // (when dealing with a retainable type), the result
8283 // initialization will create a produce. In both cases the
8284 // result will be +1, and we'll need to balance that out with
8285 // a bind.
8286 if (Expr *rebuiltLastStmt
8287 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8288 LastExpr = rebuiltLastStmt;
8289 } else {
8290 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008291 InitializedEntity::InitializeResult(LPLoc,
8292 Ty,
8293 false),
8294 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00008295 LastExpr);
8296 }
8297
John Wiegley429bb272011-04-08 18:41:53 +00008298 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008299 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008300 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008301 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00008302 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008303 else
John Wiegley429bb272011-04-08 18:41:53 +00008304 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008305 StmtExprMayBindToTemp = true;
8306 }
8307 }
8308 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008309 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008310
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008311 // FIXME: Check that expression type is complete/non-abstract; statement
8312 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008313 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8314 if (StmtExprMayBindToTemp)
8315 return MaybeBindToTemporary(ResStmtExpr);
8316 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008317}
Steve Naroffd34e9152007-08-01 22:05:33 +00008318
John McCall60d7b3a2010-08-24 06:29:42 +00008319ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008320 TypeSourceInfo *TInfo,
8321 OffsetOfComponent *CompPtr,
8322 unsigned NumComponents,
8323 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008324 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008325 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008326 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008327
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008328 // We must have at least one component that refers to the type, and the first
8329 // one is known to be a field designator. Verify that the ArgTy represents
8330 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008331 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008332 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8333 << ArgTy << TypeRange);
8334
8335 // Type must be complete per C99 7.17p3 because a declaring a variable
8336 // with an incomplete type would be ill-formed.
8337 if (!Dependent
8338 && RequireCompleteType(BuiltinLoc, ArgTy,
8339 PDiag(diag::err_offsetof_incomplete_type)
8340 << TypeRange))
8341 return ExprError();
8342
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008343 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8344 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00008345 // FIXME: This diagnostic isn't actually visible because the location is in
8346 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008347 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008348 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8349 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008350
8351 bool DidWarnAboutNonPOD = false;
8352 QualType CurrentType = ArgTy;
8353 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008354 SmallVector<OffsetOfNode, 4> Comps;
8355 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008356 for (unsigned i = 0; i != NumComponents; ++i) {
8357 const OffsetOfComponent &OC = CompPtr[i];
8358 if (OC.isBrackets) {
8359 // Offset of an array sub-field. TODO: Should we allow vector elements?
8360 if (!CurrentType->isDependentType()) {
8361 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8362 if(!AT)
8363 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8364 << CurrentType);
8365 CurrentType = AT->getElementType();
8366 } else
8367 CurrentType = Context.DependentTy;
8368
8369 // The expression must be an integral expression.
8370 // FIXME: An integral constant expression?
8371 Expr *Idx = static_cast<Expr*>(OC.U.E);
8372 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8373 !Idx->getType()->isIntegerType())
8374 return ExprError(Diag(Idx->getLocStart(),
8375 diag::err_typecheck_subscript_not_integer)
8376 << Idx->getSourceRange());
8377
8378 // Record this array index.
8379 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8380 Exprs.push_back(Idx);
8381 continue;
8382 }
8383
8384 // Offset of a field.
8385 if (CurrentType->isDependentType()) {
8386 // We have the offset of a field, but we can't look into the dependent
8387 // type. Just record the identifier of the field.
8388 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8389 CurrentType = Context.DependentTy;
8390 continue;
8391 }
8392
8393 // We need to have a complete type to look into.
8394 if (RequireCompleteType(OC.LocStart, CurrentType,
8395 diag::err_offsetof_incomplete_type))
8396 return ExprError();
8397
8398 // Look for the designated field.
8399 const RecordType *RC = CurrentType->getAs<RecordType>();
8400 if (!RC)
8401 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8402 << CurrentType);
8403 RecordDecl *RD = RC->getDecl();
8404
8405 // C++ [lib.support.types]p5:
8406 // The macro offsetof accepts a restricted set of type arguments in this
8407 // International Standard. type shall be a POD structure or a POD union
8408 // (clause 9).
8409 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8410 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00008411 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008412 PDiag(diag::warn_offsetof_non_pod_type)
8413 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8414 << CurrentType))
8415 DidWarnAboutNonPOD = true;
8416 }
8417
8418 // Look for the field.
8419 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8420 LookupQualifiedName(R, RD);
8421 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00008422 IndirectFieldDecl *IndirectMemberDecl = 0;
8423 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00008424 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00008425 MemberDecl = IndirectMemberDecl->getAnonField();
8426 }
8427
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008428 if (!MemberDecl)
8429 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8430 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8431 OC.LocEnd));
8432
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00008433 // C99 7.17p3:
8434 // (If the specified member is a bit-field, the behavior is undefined.)
8435 //
8436 // We diagnose this as an error.
8437 if (MemberDecl->getBitWidth()) {
8438 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8439 << MemberDecl->getDeclName()
8440 << SourceRange(BuiltinLoc, RParenLoc);
8441 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8442 return ExprError();
8443 }
Eli Friedman19410a72010-08-05 10:11:36 +00008444
8445 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00008446 if (IndirectMemberDecl)
8447 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00008448
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008449 // If the member was found in a base class, introduce OffsetOfNodes for
8450 // the base class indirections.
8451 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8452 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00008453 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008454 CXXBasePath &Path = Paths.front();
8455 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8456 B != BEnd; ++B)
8457 Comps.push_back(OffsetOfNode(B->Base));
8458 }
Eli Friedman19410a72010-08-05 10:11:36 +00008459
Francois Pichet87c2e122010-11-21 06:08:52 +00008460 if (IndirectMemberDecl) {
8461 for (IndirectFieldDecl::chain_iterator FI =
8462 IndirectMemberDecl->chain_begin(),
8463 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8464 assert(isa<FieldDecl>(*FI));
8465 Comps.push_back(OffsetOfNode(OC.LocStart,
8466 cast<FieldDecl>(*FI), OC.LocEnd));
8467 }
8468 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008469 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00008470
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008471 CurrentType = MemberDecl->getType().getNonReferenceType();
8472 }
8473
8474 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8475 TInfo, Comps.data(), Comps.size(),
8476 Exprs.data(), Exprs.size(), RParenLoc));
8477}
Mike Stumpeed9cac2009-02-19 03:04:26 +00008478
John McCall60d7b3a2010-08-24 06:29:42 +00008479ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00008480 SourceLocation BuiltinLoc,
8481 SourceLocation TypeLoc,
8482 ParsedType argty,
8483 OffsetOfComponent *CompPtr,
8484 unsigned NumComponents,
8485 SourceLocation RPLoc) {
8486
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008487 TypeSourceInfo *ArgTInfo;
8488 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8489 if (ArgTy.isNull())
8490 return ExprError();
8491
Eli Friedman5a15dc12010-08-05 10:15:45 +00008492 if (!ArgTInfo)
8493 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8494
8495 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8496 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008497}
8498
8499
John McCall60d7b3a2010-08-24 06:29:42 +00008500ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008501 Expr *CondExpr,
8502 Expr *LHSExpr, Expr *RHSExpr,
8503 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00008504 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8505
John McCallf89e55a2010-11-18 06:31:45 +00008506 ExprValueKind VK = VK_RValue;
8507 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00008508 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00008509 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00008510 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00008511 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00008512 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00008513 } else {
8514 // The conditional expression is required to be a constant expression.
8515 llvm::APSInt condEval(32);
8516 SourceLocation ExpLoc;
8517 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00008518 return ExprError(Diag(ExpLoc,
8519 diag::err_typecheck_choose_expr_requires_constant)
8520 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00008521
Sebastian Redl28507842009-02-26 14:39:58 +00008522 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00008523 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8524
8525 resType = ActiveExpr->getType();
8526 ValueDependent = ActiveExpr->isValueDependent();
8527 VK = ActiveExpr->getValueKind();
8528 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00008529 }
8530
Sebastian Redlf53597f2009-03-15 17:47:39 +00008531 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008532 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00008533 resType->isDependentType(),
8534 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00008535}
8536
Steve Naroff4eb206b2008-09-03 18:15:37 +00008537//===----------------------------------------------------------------------===//
8538// Clang Extensions.
8539//===----------------------------------------------------------------------===//
8540
8541/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00008542void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008543 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8544 PushBlockScope(BlockScope, Block);
8545 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008546 if (BlockScope)
8547 PushDeclContext(BlockScope, Block);
8548 else
8549 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00008550}
8551
Mike Stump98eb8a72009-02-04 22:31:32 +00008552void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00008553 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00008554 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008555 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008556
John McCallbf1a0282010-06-04 23:28:52 +00008557 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00008558 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00008559
John McCall711c52b2011-01-05 12:14:39 +00008560 // GetTypeForDeclarator always produces a function type for a block
8561 // literal signature. Furthermore, it is always a FunctionProtoType
8562 // unless the function was written with a typedef.
8563 assert(T->isFunctionType() &&
8564 "GetTypeForDeclarator made a non-function block signature");
8565
8566 // Look for an explicit signature in that function type.
8567 FunctionProtoTypeLoc ExplicitSignature;
8568
8569 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8570 if (isa<FunctionProtoTypeLoc>(tmp)) {
8571 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8572
8573 // Check whether that explicit signature was synthesized by
8574 // GetTypeForDeclarator. If so, don't save that as part of the
8575 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00008576 if (ExplicitSignature.getLocalRangeBegin() ==
8577 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00008578 // This would be much cheaper if we stored TypeLocs instead of
8579 // TypeSourceInfos.
8580 TypeLoc Result = ExplicitSignature.getResultLoc();
8581 unsigned Size = Result.getFullDataSize();
8582 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8583 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8584
8585 ExplicitSignature = FunctionProtoTypeLoc();
8586 }
John McCall82dc0092010-06-04 11:21:44 +00008587 }
Mike Stump1eb44332009-09-09 15:08:12 +00008588
John McCall711c52b2011-01-05 12:14:39 +00008589 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8590 CurBlock->FunctionType = T;
8591
8592 const FunctionType *Fn = T->getAs<FunctionType>();
8593 QualType RetTy = Fn->getResultType();
8594 bool isVariadic =
8595 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8596
John McCallc71a4912010-06-04 19:02:56 +00008597 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00008598
John McCall82dc0092010-06-04 11:21:44 +00008599 // Don't allow returning a objc interface by value.
8600 if (RetTy->isObjCObjectType()) {
8601 Diag(ParamInfo.getSourceRange().getBegin(),
8602 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8603 return;
8604 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008605
John McCall82dc0092010-06-04 11:21:44 +00008606 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00008607 // return type. TODO: what should we do with declarators like:
8608 // ^ * { ... }
8609 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00008610 if (RetTy != Context.DependentTy)
8611 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008612
John McCall82dc0092010-06-04 11:21:44 +00008613 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008614 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00008615 if (ExplicitSignature) {
8616 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8617 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008618 if (Param->getIdentifier() == 0 &&
8619 !Param->isImplicit() &&
8620 !Param->isInvalidDecl() &&
8621 !getLangOptions().CPlusPlus)
8622 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00008623 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008624 }
John McCall82dc0092010-06-04 11:21:44 +00008625
8626 // Fake up parameter variables if we have a typedef, like
8627 // ^ fntype { ... }
8628 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8629 for (FunctionProtoType::arg_type_iterator
8630 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8631 ParmVarDecl *Param =
8632 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8633 ParamInfo.getSourceRange().getBegin(),
8634 *I);
John McCallc71a4912010-06-04 19:02:56 +00008635 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00008636 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008637 }
John McCall82dc0092010-06-04 11:21:44 +00008638
John McCallc71a4912010-06-04 19:02:56 +00008639 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00008640 if (!Params.empty()) {
John McCallc71a4912010-06-04 19:02:56 +00008641 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregor82aa7132010-11-01 18:37:59 +00008642 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8643 CurBlock->TheDecl->param_end(),
8644 /*CheckParameterNames=*/false);
8645 }
8646
John McCall82dc0092010-06-04 11:21:44 +00008647 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008648 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00008649
John McCallc71a4912010-06-04 19:02:56 +00008650 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00008651 Diag(ParamInfo.getAttributes()->getLoc(),
8652 diag::warn_attribute_sentinel_not_variadic) << 1;
8653 // FIXME: remove the attribute.
8654 }
8655
8656 // Put the parameter variables in scope. We can bail out immediately
8657 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00008658 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00008659 return;
8660
Steve Naroff090276f2008-10-10 01:28:17 +00008661 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00008662 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8663 (*AI)->setOwningFunction(CurBlock->TheDecl);
8664
Steve Naroff090276f2008-10-10 01:28:17 +00008665 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00008666 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008667 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00008668
Steve Naroff090276f2008-10-10 01:28:17 +00008669 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00008670 }
John McCall7a9813c2010-01-22 00:28:27 +00008671 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008672}
8673
8674/// ActOnBlockError - If there is an error parsing a block, this callback
8675/// is invoked to pop the information about the block from the action impl.
8676void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00008677 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00008678 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008679 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008680}
8681
8682/// ActOnBlockStmtExpr - This is called when the body of a block statement
8683/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00008684ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00008685 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00008686 // If blocks are disabled, emit an error.
8687 if (!LangOpts.Blocks)
8688 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00008689
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008690 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008691
Steve Naroff090276f2008-10-10 01:28:17 +00008692 PopDeclContext();
8693
Steve Naroff4eb206b2008-09-03 18:15:37 +00008694 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00008695 if (!BSI->ReturnType.isNull())
8696 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008697
Mike Stump56925862009-07-28 22:04:01 +00008698 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008699 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00008700
John McCall469a1eb2011-02-02 13:00:07 +00008701 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00008702 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8703 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00008704
John McCallc71a4912010-06-04 19:02:56 +00008705 // If the user wrote a function type in some form, try to use that.
8706 if (!BSI->FunctionType.isNull()) {
8707 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8708
8709 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8710 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8711
8712 // Turn protoless block types into nullary block types.
8713 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00008714 FunctionProtoType::ExtProtoInfo EPI;
8715 EPI.ExtInfo = Ext;
8716 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008717
8718 // Otherwise, if we don't need to change anything about the function type,
8719 // preserve its sugar structure.
8720 } else if (FTy->getResultType() == RetTy &&
8721 (!NoReturn || FTy->getNoReturnAttr())) {
8722 BlockTy = BSI->FunctionType;
8723
8724 // Otherwise, make the minimal modifications to the function type.
8725 } else {
8726 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00008727 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8728 EPI.TypeQuals = 0; // FIXME: silently?
8729 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00008730 BlockTy = Context.getFunctionType(RetTy,
8731 FPT->arg_type_begin(),
8732 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00008733 EPI);
John McCallc71a4912010-06-04 19:02:56 +00008734 }
8735
8736 // If we don't have a function type, just build one from nothing.
8737 } else {
John McCalle23cf432010-12-14 08:05:40 +00008738 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00008739 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00008740 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008741 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008742
John McCallc71a4912010-06-04 19:02:56 +00008743 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8744 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00008745 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008746
Chris Lattner17a78302009-04-19 05:28:12 +00008747 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00008748 if (getCurFunction()->NeedsScopeChecking() &&
8749 !hasAnyUnrecoverableErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00008750 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00008751
Chris Lattnere476bdc2011-02-17 23:58:47 +00008752 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008753
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +00008754 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8755 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8756 const VarDecl *variable = ci->getVariable();
8757 QualType T = variable->getType();
8758 QualType::DestructionKind destructKind = T.isDestructedType();
8759 if (destructKind != QualType::DK_none)
8760 getCurFunction()->setHasBranchProtectedScope();
8761 }
8762
Benjamin Kramerd2486192011-07-12 14:11:05 +00008763 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8764 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8765 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8766
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008767 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00008768}
8769
John McCall60d7b3a2010-08-24 06:29:42 +00008770ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallb3d87482010-08-24 05:47:05 +00008771 Expr *expr, ParsedType type,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008772 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008773 TypeSourceInfo *TInfo;
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008774 GetTypeFromParser(type, &TInfo);
John McCall9ae2f072010-08-23 23:25:46 +00008775 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008776}
8777
John McCall60d7b3a2010-08-24 06:29:42 +00008778ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00008779 Expr *E, TypeSourceInfo *TInfo,
8780 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008781 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00008782
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008783 // Get the va_list type
8784 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008785 if (VaListType->isArrayType()) {
8786 // Deal with implicit array decay; for example, on x86-64,
8787 // va_list is an array, but it's supposed to decay to
8788 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008789 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00008790 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00008791 ExprResult Result = UsualUnaryConversions(E);
8792 if (Result.isInvalid())
8793 return ExprError();
8794 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008795 } else {
8796 // Otherwise, the va_list argument must be an l-value because
8797 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00008798 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00008799 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00008800 return ExprError();
8801 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008802
Douglas Gregordd027302009-05-19 23:10:31 +00008803 if (!E->isTypeDependent() &&
8804 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00008805 return ExprError(Diag(E->getLocStart(),
8806 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008807 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00008808 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008809
David Majnemer0adde122011-06-14 05:17:32 +00008810 if (!TInfo->getType()->isDependentType()) {
8811 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8812 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8813 << TInfo->getTypeLoc().getSourceRange()))
8814 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00008815
David Majnemer0adde122011-06-14 05:17:32 +00008816 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8817 TInfo->getType(),
8818 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8819 << TInfo->getTypeLoc().getSourceRange()))
8820 return ExprError();
8821
Douglas Gregor4eb75222011-07-30 06:45:27 +00008822 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00008823 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00008824 TInfo->getType()->isObjCLifetimeType()
8825 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8826 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00008827 << TInfo->getType()
8828 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00008829 }
Eli Friedman46d37c12011-07-11 21:45:59 +00008830
8831 // Check for va_arg where arguments of the given type will be promoted
8832 // (i.e. this va_arg is guaranteed to have undefined behavior).
8833 QualType PromoteType;
8834 if (TInfo->getType()->isPromotableIntegerType()) {
8835 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8836 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8837 PromoteType = QualType();
8838 }
8839 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8840 PromoteType = Context.DoubleTy;
8841 if (!PromoteType.isNull())
8842 Diag(TInfo->getTypeLoc().getBeginLoc(),
8843 diag::warn_second_parameter_to_va_arg_never_compatible)
8844 << TInfo->getType()
8845 << PromoteType
8846 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00008847 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008848
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008849 QualType T = TInfo->getType().getNonLValueExprType(Context);
8850 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008851}
8852
John McCall60d7b3a2010-08-24 06:29:42 +00008853ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008854 // The type of __null will be int or long, depending on the size of
8855 // pointers on the target.
8856 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00008857 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
8858 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008859 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00008860 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008861 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00008862 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008863 Ty = Context.LongLongTy;
8864 else {
8865 assert(!"I don't know size of pointer!");
8866 Ty = Context.IntTy;
8867 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008868
Sebastian Redlf53597f2009-03-15 17:47:39 +00008869 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008870}
8871
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008872static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00008873 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008874 if (!SemaRef.getLangOptions().ObjC1)
8875 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008876
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008877 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8878 if (!PT)
8879 return;
8880
8881 // Check if the destination is of type 'id'.
8882 if (!PT->isObjCIdType()) {
8883 // Check if the destination is the 'NSString' interface.
8884 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8885 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8886 return;
8887 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008888
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008889 // Strip off any parens and casts.
8890 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregor5cee1192011-07-27 05:40:30 +00008891 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008892 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008893
Douglas Gregor849b2432010-03-31 17:46:05 +00008894 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008895}
8896
Chris Lattner5cf216b2008-01-04 18:04:52 +00008897bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8898 SourceLocation Loc,
8899 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00008900 Expr *SrcExpr, AssignmentAction Action,
8901 bool *Complained) {
8902 if (Complained)
8903 *Complained = false;
8904
Chris Lattner5cf216b2008-01-04 18:04:52 +00008905 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00008906 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008907 bool isInvalid = false;
8908 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00008909 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00008910 ConversionFixItGenerator ConvHints;
8911 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008912
Chris Lattner5cf216b2008-01-04 18:04:52 +00008913 switch (ConvTy) {
8914 default: assert(0 && "Unknown conversion type");
8915 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008916 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00008917 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00008918 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8919 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008920 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008921 case IntToPointer:
8922 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00008923 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8924 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008925 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008926 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00008927 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00008928 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00008929 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8930 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00008931 if (Hint.isNull() && !CheckInferredResultType) {
8932 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8933 }
8934 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008935 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00008936 case IncompatiblePointerSign:
8937 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8938 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008939 case FunctionVoidPointer:
8940 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8941 break;
John McCall86c05f32011-02-01 00:10:29 +00008942 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00008943 // Perform array-to-pointer decay if necessary.
8944 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8945
John McCall86c05f32011-02-01 00:10:29 +00008946 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8947 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8948 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8949 DiagKind = diag::err_typecheck_incompatible_address_space;
8950 break;
John McCallf85e1932011-06-15 23:02:42 +00008951
8952
8953 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008954 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00008955 break;
John McCall86c05f32011-02-01 00:10:29 +00008956 }
8957
8958 llvm_unreachable("unknown error case for discarding qualifiers!");
8959 // fallthrough
8960 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00008961 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00008962 // If the qualifiers lost were because we were applying the
8963 // (deprecated) C++ conversion from a string literal to a char*
8964 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8965 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00008966 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00008967 // bit of refactoring (so that the second argument is an
8968 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00008969 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00008970 // C++ semantics.
8971 if (getLangOptions().CPlusPlus &&
8972 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8973 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008974 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8975 break;
Sean Huntc9132b62009-11-08 07:46:34 +00008976 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00008977 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00008978 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00008979 case IntToBlockPointer:
8980 DiagKind = diag::err_int_to_block_pointer;
8981 break;
8982 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00008983 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00008984 break;
Steve Naroff39579072008-10-14 22:18:38 +00008985 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00008986 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00008987 // it can give a more specific diagnostic.
8988 DiagKind = diag::warn_incompatible_qualified_id;
8989 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00008990 case IncompatibleVectors:
8991 DiagKind = diag::warn_incompatible_vectors;
8992 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00008993 case IncompatibleObjCWeakRef:
8994 DiagKind = diag::err_arc_weak_unavailable_assign;
8995 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008996 case Incompatible:
8997 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00008998 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8999 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009000 isInvalid = true;
9001 break;
9002 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009003
Douglas Gregord4eea832010-04-09 00:35:39 +00009004 QualType FirstType, SecondType;
9005 switch (Action) {
9006 case AA_Assigning:
9007 case AA_Initializing:
9008 // The destination type comes first.
9009 FirstType = DstType;
9010 SecondType = SrcType;
9011 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009012
Douglas Gregord4eea832010-04-09 00:35:39 +00009013 case AA_Returning:
9014 case AA_Passing:
9015 case AA_Converting:
9016 case AA_Sending:
9017 case AA_Casting:
9018 // The source type comes first.
9019 FirstType = SrcType;
9020 SecondType = DstType;
9021 break;
9022 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009023
Anna Zaks67221552011-07-28 19:51:27 +00009024 PartialDiagnostic FDiag = PDiag(DiagKind);
9025 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9026
9027 // If we can fix the conversion, suggest the FixIts.
9028 assert(ConvHints.isNull() || Hint.isNull());
9029 if (!ConvHints.isNull()) {
9030 for (llvm::SmallVector<FixItHint, 1>::iterator
9031 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
9032 HI != HE; ++HI)
9033 FDiag << *HI;
9034 } else {
9035 FDiag << Hint;
9036 }
9037 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9038
9039 Diag(Loc, FDiag);
9040
Douglas Gregor926df6c2011-06-11 01:09:30 +00009041 if (CheckInferredResultType)
9042 EmitRelatedResultTypeNote(SrcExpr);
9043
Douglas Gregora41a8c52010-04-22 00:20:18 +00009044 if (Complained)
9045 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009046 return isInvalid;
9047}
Anders Carlssone21555e2008-11-30 19:50:32 +00009048
Chris Lattner3bf68932009-04-25 21:59:05 +00009049bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009050 llvm::APSInt ICEResult;
9051 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9052 if (Result)
9053 *Result = ICEResult;
9054 return false;
9055 }
9056
Anders Carlssone21555e2008-11-30 19:50:32 +00009057 Expr::EvalResult EvalResult;
9058
Mike Stumpeed9cac2009-02-19 03:04:26 +00009059 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00009060 EvalResult.HasSideEffects) {
9061 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9062
9063 if (EvalResult.Diag) {
9064 // We only show the note if it's not the usual "invalid subexpression"
9065 // or if it's actually in a subexpression.
9066 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9067 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9068 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9069 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009070
Anders Carlssone21555e2008-11-30 19:50:32 +00009071 return true;
9072 }
9073
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009074 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9075 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00009076
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009077 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009078 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9079 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009080 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009081
Anders Carlssone21555e2008-11-30 19:50:32 +00009082 if (Result)
9083 *Result = EvalResult.Val.getInt();
9084 return false;
9085}
Douglas Gregore0762c92009-06-19 23:52:42 +00009086
Douglas Gregor2afce722009-11-26 00:44:06 +00009087void
Mike Stump1eb44332009-09-09 15:08:12 +00009088Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009089 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +00009090 ExpressionEvaluationContextRecord(NewContext,
9091 ExprTemporaries.size(),
9092 ExprNeedsCleanups));
9093 ExprNeedsCleanups = false;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009094}
9095
Richard Trieu67e29332011-08-02 04:35:43 +00009096void Sema::PopExpressionEvaluationContext() {
Douglas Gregor2afce722009-11-26 00:44:06 +00009097 // Pop the current expression evaluation context off the stack.
9098 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9099 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009100
Douglas Gregor06d33692009-12-12 07:57:52 +00009101 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9102 if (Rec.PotentiallyReferenced) {
9103 // Mark any remaining declarations in the current position of the stack
9104 // as "referenced". If they were not meant to be referenced, semantic
9105 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009106 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00009107 I = Rec.PotentiallyReferenced->begin(),
9108 IEnd = Rec.PotentiallyReferenced->end();
9109 I != IEnd; ++I)
9110 MarkDeclarationReferenced(I->first, I->second);
9111 }
9112
9113 if (Rec.PotentiallyDiagnosed) {
9114 // Emit any pending diagnostics.
9115 for (PotentiallyEmittedDiagnostics::iterator
9116 I = Rec.PotentiallyDiagnosed->begin(),
9117 IEnd = Rec.PotentiallyDiagnosed->end();
9118 I != IEnd; ++I)
9119 Diag(I->first, I->second);
9120 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009121 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009122
9123 // When are coming out of an unevaluated context, clear out any
9124 // temporaries that we may have created as part of the evaluation of
9125 // the expression in that context: they aren't relevant because they
9126 // will never be constructed.
John McCallf85e1932011-06-15 23:02:42 +00009127 if (Rec.Context == Unevaluated) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009128 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9129 ExprTemporaries.end());
John McCallf85e1932011-06-15 23:02:42 +00009130 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9131
9132 // Otherwise, merge the contexts together.
9133 } else {
9134 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9135 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009136
9137 // Destroy the popped expression evaluation record.
9138 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009139}
Douglas Gregore0762c92009-06-19 23:52:42 +00009140
John McCallf85e1932011-06-15 23:02:42 +00009141void Sema::DiscardCleanupsInEvaluationContext() {
9142 ExprTemporaries.erase(
9143 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9144 ExprTemporaries.end());
9145 ExprNeedsCleanups = false;
9146}
9147
Douglas Gregore0762c92009-06-19 23:52:42 +00009148/// \brief Note that the given declaration was referenced in the source code.
9149///
9150/// This routine should be invoke whenever a given declaration is referenced
9151/// in the source code, and where that reference occurred. If this declaration
9152/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9153/// C99 6.9p3), then the declaration will be marked as used.
9154///
9155/// \param Loc the location where the declaration was referenced.
9156///
9157/// \param D the declaration that has been referenced by the source code.
9158void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9159 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009160
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +00009161 D->setReferenced();
9162
Douglas Gregorc070cc62010-06-17 23:14:26 +00009163 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009164 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009165
Richard Trieu67e29332011-08-02 04:35:43 +00009166 // Mark a parameter or variable declaration "used", regardless of whether
9167 // we're in a template or not. The reason for this is that unevaluated
9168 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9169 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009170 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009171 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009172 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009173 return;
9174 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009175
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009176 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9177 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009178
Douglas Gregore0762c92009-06-19 23:52:42 +00009179 // Do not mark anything as "used" within a dependent context; wait for
9180 // an instantiation.
9181 if (CurContext->isDependentContext())
9182 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009183
Douglas Gregor2afce722009-11-26 00:44:06 +00009184 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009185 case Unevaluated:
9186 // We are in an expression that is not potentially evaluated; do nothing.
9187 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009188
Douglas Gregorac7610d2009-06-22 20:57:11 +00009189 case PotentiallyEvaluated:
9190 // We are in a potentially-evaluated expression, so this declaration is
9191 // "used"; handle this below.
9192 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009193
Douglas Gregorac7610d2009-06-22 20:57:11 +00009194 case PotentiallyPotentiallyEvaluated:
9195 // We are in an expression that may be potentially evaluated; queue this
9196 // declaration reference until we know whether the expression is
9197 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009198 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009199 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009200
9201 case PotentiallyEvaluatedIfUsed:
9202 // Referenced declarations will only be used if the construct in the
9203 // containing expression is used.
9204 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009205 }
Mike Stump1eb44332009-09-09 15:08:12 +00009206
Douglas Gregore0762c92009-06-19 23:52:42 +00009207 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009208 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009209 if (Constructor->isDefaulted()) {
9210 if (Constructor->isDefaultConstructor()) {
9211 if (Constructor->isTrivial())
9212 return;
9213 if (!Constructor->isUsed(false))
9214 DefineImplicitDefaultConstructor(Loc, Constructor);
9215 } else if (Constructor->isCopyConstructor()) {
9216 if (!Constructor->isUsed(false))
9217 DefineImplicitCopyConstructor(Loc, Constructor);
9218 } else if (Constructor->isMoveConstructor()) {
9219 if (!Constructor->isUsed(false))
9220 DefineImplicitMoveConstructor(Loc, Constructor);
9221 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009222 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009223
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009224 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009225 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00009226 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009227 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009228 if (Destructor->isVirtual())
9229 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009230 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Sean Hunt2b188082011-05-14 05:23:28 +00009231 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009232 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009233 if (!MethodDecl->isUsed(false)) {
9234 if (MethodDecl->isCopyAssignmentOperator())
9235 DefineImplicitCopyAssignment(Loc, MethodDecl);
9236 else
9237 DefineImplicitMoveAssignment(Loc, MethodDecl);
9238 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009239 } else if (MethodDecl->isVirtual())
9240 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009241 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009242 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +00009243 // Recursive functions should be marked when used from another function.
9244 if (CurContext == Function) return;
9245
Mike Stump1eb44332009-09-09 15:08:12 +00009246 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009247 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009248 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009249 bool AlreadyInstantiated = false;
9250 if (FunctionTemplateSpecializationInfo *SpecInfo
9251 = Function->getTemplateSpecializationInfo()) {
9252 if (SpecInfo->getPointOfInstantiation().isInvalid())
9253 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009254 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009255 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009256 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009257 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009258 = Function->getMemberSpecializationInfo()) {
9259 if (MSInfo->getPointOfInstantiation().isInvalid())
9260 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009261 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009262 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009263 AlreadyInstantiated = true;
9264 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009265
Douglas Gregor60406be2010-01-16 22:29:39 +00009266 if (!AlreadyInstantiated) {
9267 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9268 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9269 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9270 Loc));
9271 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00009272 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00009273 }
John McCall15e310a2011-02-19 02:53:41 +00009274 } else {
9275 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +00009276 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9277 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00009278 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00009279 MarkDeclarationReferenced(Loc, *i);
9280 }
John McCall15e310a2011-02-19 02:53:41 +00009281 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009282
John McCall15e310a2011-02-19 02:53:41 +00009283 // Keep track of used but undefined functions.
9284 if (!Function->isPure() && !Function->hasBody() &&
9285 Function->getLinkage() != ExternalLinkage) {
9286 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9287 if (old.isInvalid()) old = Loc;
9288 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00009289
John McCall15e310a2011-02-19 02:53:41 +00009290 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +00009291 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009292 }
Mike Stump1eb44332009-09-09 15:08:12 +00009293
Douglas Gregore0762c92009-06-19 23:52:42 +00009294 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00009295 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00009296 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009297 Var->getInstantiatedFromStaticDataMember()) {
9298 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9299 assert(MSInfo && "Missing member specialization information?");
9300 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9301 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9302 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redlf79a7192011-04-29 08:19:30 +00009303 // This is a modification of an existing AST node. Notify listeners.
9304 if (ASTMutationListener *L = getASTMutationListener())
9305 L->StaticDataMemberInstantiated(Var);
Chandler Carruth62c78d52010-08-25 08:44:16 +00009306 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009307 }
9308 }
Mike Stump1eb44332009-09-09 15:08:12 +00009309
John McCall77efc682011-02-21 19:25:48 +00009310 // Keep track of used but undefined variables. We make a hole in
9311 // the warning for static const data members with in-line
9312 // initializers.
John McCall15e310a2011-02-19 02:53:41 +00009313 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall77efc682011-02-21 19:25:48 +00009314 && Var->getLinkage() != ExternalLinkage
9315 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall15e310a2011-02-19 02:53:41 +00009316 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9317 if (old.isInvalid()) old = Loc;
9318 }
Douglas Gregor7caa6822009-07-24 20:34:43 +00009319
Douglas Gregore0762c92009-06-19 23:52:42 +00009320 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00009321 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00009322 }
Douglas Gregore0762c92009-06-19 23:52:42 +00009323}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009324
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009325namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009326 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009327 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009328 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009329 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9330 Sema &S;
9331 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009332
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009333 public:
9334 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009335
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009336 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009337
9338 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9339 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009340 };
9341}
9342
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009343bool MarkReferencedDecls::TraverseTemplateArgument(
9344 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009345 if (Arg.getKind() == TemplateArgument::Declaration) {
9346 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9347 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009348
9349 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009350}
9351
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009352bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009353 if (ClassTemplateSpecializationDecl *Spec
9354 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9355 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +00009356 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009357 }
9358
Chandler Carruthe3e210c2010-06-10 10:31:57 +00009359 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009360}
9361
9362void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9363 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009364 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009365}
9366
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009367namespace {
9368 /// \brief Helper class that marks all of the declarations referenced by
9369 /// potentially-evaluated subexpressions as "referenced".
9370 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9371 Sema &S;
9372
9373 public:
9374 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9375
9376 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9377
9378 void VisitDeclRefExpr(DeclRefExpr *E) {
9379 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9380 }
9381
9382 void VisitMemberExpr(MemberExpr *E) {
9383 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009384 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009385 }
9386
9387 void VisitCXXNewExpr(CXXNewExpr *E) {
9388 if (E->getConstructor())
9389 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9390 if (E->getOperatorNew())
9391 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9392 if (E->getOperatorDelete())
9393 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009394 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009395 }
9396
9397 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9398 if (E->getOperatorDelete())
9399 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +00009400 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9401 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9402 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9403 S.MarkDeclarationReferenced(E->getLocStart(),
9404 S.LookupDestructor(Record));
9405 }
9406
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009407 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009408 }
9409
9410 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9411 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009412 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009413 }
9414
9415 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9416 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9417 }
Douglas Gregor102ff972010-10-19 17:17:35 +00009418
9419 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9420 Visit(E->getExpr());
9421 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009422 };
9423}
9424
9425/// \brief Mark any declarations that appear within this expression or any
9426/// potentially-evaluated subexpressions as "referenced".
9427void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9428 EvaluatedExprMarker(*this).Visit(E);
9429}
9430
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009431/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9432/// of the program being compiled.
9433///
9434/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009435/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009436/// possibility that the code will actually be executable. Code in sizeof()
9437/// expressions, code used only during overload resolution, etc., are not
9438/// potentially evaluated. This routine will suppress such diagnostics or,
9439/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009440/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009441/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009442///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009443/// This routine should be used for all diagnostics that describe the run-time
9444/// behavior of a program, such as passing a non-POD value through an ellipsis.
9445/// Failure to do so will likely result in spurious diagnostics or failures
9446/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek762696f2011-02-23 01:51:43 +00009447bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009448 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +00009449 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009450 case Unevaluated:
9451 // The argument will never be evaluated, so don't complain.
9452 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009453
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009454 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009455 case PotentiallyEvaluatedIfUsed:
Ted Kremenek351ba912011-02-23 01:52:04 +00009456 if (stmt && getCurFunctionOrMethodDecl()) {
9457 FunctionScopes.back()->PossiblyUnreachableDiags.
9458 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9459 }
9460 else
9461 Diag(Loc, PD);
9462
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009463 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009464
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009465 case PotentiallyPotentiallyEvaluated:
9466 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9467 break;
9468 }
9469
9470 return false;
9471}
9472
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009473bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9474 CallExpr *CE, FunctionDecl *FD) {
9475 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9476 return false;
9477
9478 PartialDiagnostic Note =
9479 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9480 << FD->getDeclName() : PDiag();
9481 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009482
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009483 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009484 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009485 PDiag(diag::err_call_function_incomplete_return)
9486 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009487 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009488 << CE->getSourceRange(),
9489 std::make_pair(NoteLoc, Note)))
9490 return true;
9491
9492 return false;
9493}
9494
Douglas Gregor92c3a042011-01-19 16:50:08 +00009495// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +00009496// will prevent this condition from triggering, which is what we want.
9497void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9498 SourceLocation Loc;
9499
John McCalla52ef082009-11-11 02:41:58 +00009500 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +00009501 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +00009502
Chandler Carruthb33c19f2011-08-16 22:30:10 +00009503 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +00009504 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +00009505 return;
9506
Douglas Gregor92c3a042011-01-19 16:50:08 +00009507 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9508
John McCallc8d8ac52009-11-12 00:06:05 +00009509 // Greylist some idioms by putting them into a warning subcategory.
9510 if (ObjCMessageExpr *ME
9511 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9512 Selector Sel = ME->getSelector();
9513
John McCallc8d8ac52009-11-12 00:06:05 +00009514 // self = [<foo> init...]
Douglas Gregor813d8342011-02-18 22:29:55 +00009515 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +00009516 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9517
9518 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +00009519 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +00009520 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9521 }
John McCalla52ef082009-11-11 02:41:58 +00009522
John McCall5a881bb2009-10-12 21:59:07 +00009523 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +00009524 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +00009525 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +00009526 return;
9527
Douglas Gregor92c3a042011-01-19 16:50:08 +00009528 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +00009529 Loc = Op->getOperatorLoc();
9530 } else {
9531 // Not an assignment.
9532 return;
9533 }
9534
Douglas Gregor55b38842010-04-14 16:09:52 +00009535 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +00009536
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009537 SourceLocation Open = E->getSourceRange().getBegin();
9538 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9539 Diag(Loc, diag::note_condition_assign_silence)
9540 << FixItHint::CreateInsertion(Open, "(")
9541 << FixItHint::CreateInsertion(Close, ")");
9542
Douglas Gregor92c3a042011-01-19 16:50:08 +00009543 if (IsOrAssign)
9544 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9545 << FixItHint::CreateReplacement(Loc, "!=");
9546 else
9547 Diag(Loc, diag::note_condition_assign_to_comparison)
9548 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +00009549}
9550
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009551/// \brief Redundant parentheses over an equality comparison can indicate
9552/// that the user intended an assignment used as condition.
9553void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009554 // Don't warn if the parens came from a macro.
9555 SourceLocation parenLoc = parenE->getLocStart();
9556 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9557 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +00009558 // Don't warn for dependent expressions.
9559 if (parenE->isTypeDependent())
9560 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009561
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009562 Expr *E = parenE->IgnoreParens();
9563
9564 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +00009565 if (opE->getOpcode() == BO_EQ &&
9566 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9567 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009568 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +00009569
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009570 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009571 Diag(Loc, diag::note_equality_comparison_silence)
9572 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9573 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009574 Diag(Loc, diag::note_equality_comparison_to_assign)
9575 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009576 }
9577}
9578
John Wiegley429bb272011-04-08 18:41:53 +00009579ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +00009580 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009581 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9582 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +00009583
John McCall864c0412011-04-26 20:42:42 +00009584 ExprResult result = CheckPlaceholderExpr(E);
9585 if (result.isInvalid()) return ExprError();
9586 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00009587
John McCall864c0412011-04-26 20:42:42 +00009588 if (!E->isTypeDependent()) {
John McCallf6a16482010-12-04 03:47:34 +00009589 if (getLangOptions().CPlusPlus)
9590 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9591
John Wiegley429bb272011-04-08 18:41:53 +00009592 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9593 if (ERes.isInvalid())
9594 return ExprError();
9595 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +00009596
9597 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +00009598 if (!T->isScalarType()) { // C99 6.8.4.1p1
9599 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9600 << T << E->getSourceRange();
9601 return ExprError();
9602 }
John McCall5a881bb2009-10-12 21:59:07 +00009603 }
9604
John Wiegley429bb272011-04-08 18:41:53 +00009605 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +00009606}
Douglas Gregor586596f2010-05-06 17:25:47 +00009607
John McCall60d7b3a2010-08-24 06:29:42 +00009608ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9609 Expr *Sub) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +00009610 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +00009611 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009612
9613 return CheckBooleanCondition(Sub, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +00009614}
John McCall2a984ca2010-10-12 00:20:44 +00009615
John McCall1de4d4e2011-04-07 08:22:57 +00009616namespace {
John McCall755d8492011-04-12 00:42:48 +00009617 /// A visitor for rebuilding a call to an __unknown_any expression
9618 /// to have an appropriate type.
9619 struct RebuildUnknownAnyFunction
9620 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9621
9622 Sema &S;
9623
9624 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9625
9626 ExprResult VisitStmt(Stmt *S) {
9627 llvm_unreachable("unexpected statement!");
9628 return ExprError();
9629 }
9630
9631 ExprResult VisitExpr(Expr *expr) {
9632 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
9633 << expr->getSourceRange();
9634 return ExprError();
9635 }
9636
9637 /// Rebuild an expression which simply semantically wraps another
9638 /// expression which it shares the type and value kind of.
9639 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9640 ExprResult subResult = Visit(expr->getSubExpr());
9641 if (subResult.isInvalid()) return ExprError();
9642
9643 Expr *subExpr = subResult.take();
9644 expr->setSubExpr(subExpr);
9645 expr->setType(subExpr->getType());
9646 expr->setValueKind(subExpr->getValueKind());
9647 assert(expr->getObjectKind() == OK_Ordinary);
9648 return expr;
9649 }
9650
9651 ExprResult VisitParenExpr(ParenExpr *paren) {
9652 return rebuildSugarExpr(paren);
9653 }
9654
9655 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9656 return rebuildSugarExpr(op);
9657 }
9658
9659 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9660 ExprResult subResult = Visit(op->getSubExpr());
9661 if (subResult.isInvalid()) return ExprError();
9662
9663 Expr *subExpr = subResult.take();
9664 op->setSubExpr(subExpr);
9665 op->setType(S.Context.getPointerType(subExpr->getType()));
9666 assert(op->getValueKind() == VK_RValue);
9667 assert(op->getObjectKind() == OK_Ordinary);
9668 return op;
9669 }
9670
9671 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
9672 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
9673
9674 expr->setType(decl->getType());
9675
9676 assert(expr->getValueKind() == VK_RValue);
9677 if (S.getLangOptions().CPlusPlus &&
9678 !(isa<CXXMethodDecl>(decl) &&
9679 cast<CXXMethodDecl>(decl)->isInstance()))
9680 expr->setValueKind(VK_LValue);
9681
9682 return expr;
9683 }
9684
9685 ExprResult VisitMemberExpr(MemberExpr *mem) {
9686 return resolveDecl(mem, mem->getMemberDecl());
9687 }
9688
9689 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
9690 return resolveDecl(ref, ref->getDecl());
9691 }
9692 };
9693}
9694
9695/// Given a function expression of unknown-any type, try to rebuild it
9696/// to have a function type.
9697static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
9698 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
9699 if (result.isInvalid()) return ExprError();
9700 return S.DefaultFunctionArrayConversion(result.take());
9701}
9702
9703namespace {
John McCall379b5152011-04-11 07:02:50 +00009704 /// A visitor for rebuilding an expression of type __unknown_anytype
9705 /// into one which resolves the type directly on the referring
9706 /// expression. Strict preservation of the original source
9707 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +00009708 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +00009709 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +00009710
9711 Sema &S;
9712
9713 /// The current destination type.
9714 QualType DestType;
9715
9716 RebuildUnknownAnyExpr(Sema &S, QualType castType)
9717 : S(S), DestType(castType) {}
9718
John McCalla5fc4722011-04-09 22:50:59 +00009719 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +00009720 llvm_unreachable("unexpected statement!");
John McCalla5fc4722011-04-09 22:50:59 +00009721 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009722 }
9723
John McCall379b5152011-04-11 07:02:50 +00009724 ExprResult VisitExpr(Expr *expr) {
9725 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9726 << expr->getSourceRange();
9727 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009728 }
9729
John McCall379b5152011-04-11 07:02:50 +00009730 ExprResult VisitCallExpr(CallExpr *call);
9731 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
9732
John McCalla5fc4722011-04-09 22:50:59 +00009733 /// Rebuild an expression which simply semantically wraps another
9734 /// expression which it shares the type and value kind of.
9735 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9736 ExprResult subResult = Visit(expr->getSubExpr());
John McCall755d8492011-04-12 00:42:48 +00009737 if (subResult.isInvalid()) return ExprError();
John McCalla5fc4722011-04-09 22:50:59 +00009738 Expr *subExpr = subResult.take();
9739 expr->setSubExpr(subExpr);
9740 expr->setType(subExpr->getType());
9741 expr->setValueKind(subExpr->getValueKind());
9742 assert(expr->getObjectKind() == OK_Ordinary);
9743 return expr;
9744 }
John McCall1de4d4e2011-04-07 08:22:57 +00009745
John McCalla5fc4722011-04-09 22:50:59 +00009746 ExprResult VisitParenExpr(ParenExpr *paren) {
9747 return rebuildSugarExpr(paren);
9748 }
9749
9750 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9751 return rebuildSugarExpr(op);
9752 }
9753
John McCall755d8492011-04-12 00:42:48 +00009754 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9755 const PointerType *ptr = DestType->getAs<PointerType>();
9756 if (!ptr) {
9757 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
9758 << op->getSourceRange();
9759 return ExprError();
9760 }
9761 assert(op->getValueKind() == VK_RValue);
9762 assert(op->getObjectKind() == OK_Ordinary);
9763 op->setType(DestType);
9764
9765 // Build the sub-expression as if it were an object of the pointee type.
9766 DestType = ptr->getPointeeType();
9767 ExprResult subResult = Visit(op->getSubExpr());
9768 if (subResult.isInvalid()) return ExprError();
9769 op->setSubExpr(subResult.take());
9770 return op;
9771 }
9772
John McCall379b5152011-04-11 07:02:50 +00009773 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCalla5fc4722011-04-09 22:50:59 +00009774
John McCall755d8492011-04-12 00:42:48 +00009775 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCalla5fc4722011-04-09 22:50:59 +00009776
John McCall755d8492011-04-12 00:42:48 +00009777 ExprResult VisitMemberExpr(MemberExpr *mem) {
9778 return resolveDecl(mem, mem->getMemberDecl());
9779 }
John McCalla5fc4722011-04-09 22:50:59 +00009780
9781 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall379b5152011-04-11 07:02:50 +00009782 return resolveDecl(ref, ref->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +00009783 }
9784 };
9785}
9786
John McCall379b5152011-04-11 07:02:50 +00009787/// Rebuilds a call expression which yielded __unknown_anytype.
9788ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
9789 Expr *callee = call->getCallee();
9790
9791 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +00009792 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +00009793 FK_FunctionPointer,
9794 FK_BlockPointer
9795 };
9796
9797 FnKind kind;
9798 QualType type = callee->getType();
John McCallf5307512011-04-27 00:36:17 +00009799 if (type == S.Context.BoundMemberTy) {
9800 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
9801 kind = FK_MemberFunction;
9802 type = Expr::findBoundMemberType(callee);
John McCall379b5152011-04-11 07:02:50 +00009803 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
9804 type = ptr->getPointeeType();
9805 kind = FK_FunctionPointer;
9806 } else {
9807 type = type->castAs<BlockPointerType>()->getPointeeType();
9808 kind = FK_BlockPointer;
9809 }
9810 const FunctionType *fnType = type->castAs<FunctionType>();
9811
9812 // Verify that this is a legal result type of a function.
9813 if (DestType->isArrayType() || DestType->isFunctionType()) {
9814 unsigned diagID = diag::err_func_returning_array_function;
9815 if (kind == FK_BlockPointer)
9816 diagID = diag::err_block_returning_array_function;
9817
9818 S.Diag(call->getExprLoc(), diagID)
9819 << DestType->isFunctionType() << DestType;
9820 return ExprError();
9821 }
9822
9823 // Otherwise, go ahead and set DestType as the call's result.
9824 call->setType(DestType.getNonLValueExprType(S.Context));
9825 call->setValueKind(Expr::getValueKindForType(DestType));
9826 assert(call->getObjectKind() == OK_Ordinary);
9827
9828 // Rebuild the function type, replacing the result type with DestType.
9829 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
9830 DestType = S.Context.getFunctionType(DestType,
9831 proto->arg_type_begin(),
9832 proto->getNumArgs(),
9833 proto->getExtProtoInfo());
9834 else
9835 DestType = S.Context.getFunctionNoProtoType(DestType,
9836 fnType->getExtInfo());
9837
9838 // Rebuild the appropriate pointer-to-function type.
9839 switch (kind) {
John McCallf5307512011-04-27 00:36:17 +00009840 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +00009841 // Nothing to do.
9842 break;
9843
9844 case FK_FunctionPointer:
9845 DestType = S.Context.getPointerType(DestType);
9846 break;
9847
9848 case FK_BlockPointer:
9849 DestType = S.Context.getBlockPointerType(DestType);
9850 break;
9851 }
9852
9853 // Finally, we can recurse.
9854 ExprResult calleeResult = Visit(callee);
9855 if (!calleeResult.isUsable()) return ExprError();
9856 call->setCallee(calleeResult.take());
9857
9858 // Bind a temporary if necessary.
9859 return S.MaybeBindToTemporary(call);
9860}
9861
9862ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall755d8492011-04-12 00:42:48 +00009863 // Verify that this is a legal result type of a call.
9864 if (DestType->isArrayType() || DestType->isFunctionType()) {
9865 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
9866 << DestType->isFunctionType() << DestType;
9867 return ExprError();
John McCall379b5152011-04-11 07:02:50 +00009868 }
9869
John McCall48218c62011-07-13 17:56:40 +00009870 // Rewrite the method result type if available.
9871 if (ObjCMethodDecl *method = msg->getMethodDecl()) {
9872 assert(method->getResultType() == S.Context.UnknownAnyTy);
9873 method->setResultType(DestType);
9874 }
John McCall755d8492011-04-12 00:42:48 +00009875
John McCall379b5152011-04-11 07:02:50 +00009876 // Change the type of the message.
John McCall755d8492011-04-12 00:42:48 +00009877 msg->setType(DestType.getNonReferenceType());
9878 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +00009879
John McCall755d8492011-04-12 00:42:48 +00009880 return S.MaybeBindToTemporary(msg);
John McCall379b5152011-04-11 07:02:50 +00009881}
9882
9883ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall755d8492011-04-12 00:42:48 +00009884 // The only case we should ever see here is a function-to-pointer decay.
John McCall379b5152011-04-11 07:02:50 +00009885 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall379b5152011-04-11 07:02:50 +00009886 assert(ice->getValueKind() == VK_RValue);
9887 assert(ice->getObjectKind() == OK_Ordinary);
9888
John McCall755d8492011-04-12 00:42:48 +00009889 ice->setType(DestType);
9890
John McCall379b5152011-04-11 07:02:50 +00009891 // Rebuild the sub-expression as the pointee (function) type.
9892 DestType = DestType->castAs<PointerType>()->getPointeeType();
9893
9894 ExprResult result = Visit(ice->getSubExpr());
9895 if (!result.isUsable()) return ExprError();
9896
9897 ice->setSubExpr(result.take());
9898 return S.Owned(ice);
9899}
9900
John McCall755d8492011-04-12 00:42:48 +00009901ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall379b5152011-04-11 07:02:50 +00009902 ExprValueKind valueKind = VK_LValue;
John McCall379b5152011-04-11 07:02:50 +00009903 QualType type = DestType;
9904
9905 // We know how to make this work for certain kinds of decls:
9906
9907 // - functions
John McCall755d8492011-04-12 00:42:48 +00009908 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCalla19950e2011-08-10 04:12:23 +00009909 if (const PointerType *ptr = type->getAs<PointerType>()) {
9910 DestType = ptr->getPointeeType();
9911 ExprResult result = resolveDecl(expr, decl);
9912 if (result.isInvalid()) return ExprError();
9913 return S.ImpCastExprToType(result.take(), type,
9914 CK_FunctionToPointerDecay, VK_RValue);
9915 }
9916
9917 if (!type->isFunctionType()) {
9918 S.Diag(expr->getExprLoc(), diag::err_unknown_any_function)
9919 << decl << expr->getSourceRange();
9920 return ExprError();
9921 }
John McCall379b5152011-04-11 07:02:50 +00009922
John McCallf5307512011-04-27 00:36:17 +00009923 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
9924 if (method->isInstance()) {
9925 valueKind = VK_RValue;
9926 type = S.Context.BoundMemberTy;
9927 }
9928
John McCall379b5152011-04-11 07:02:50 +00009929 // Function references aren't l-values in C.
9930 if (!S.getLangOptions().CPlusPlus)
9931 valueKind = VK_RValue;
9932
9933 // - variables
9934 } else if (isa<VarDecl>(decl)) {
John McCall755d8492011-04-12 00:42:48 +00009935 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
9936 type = refTy->getPointeeType();
John McCall379b5152011-04-11 07:02:50 +00009937 } else if (type->isFunctionType()) {
John McCall755d8492011-04-12 00:42:48 +00009938 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
9939 << decl << expr->getSourceRange();
9940 return ExprError();
John McCall379b5152011-04-11 07:02:50 +00009941 }
9942
9943 // - nothing else
9944 } else {
9945 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9946 << decl << expr->getSourceRange();
9947 return ExprError();
9948 }
9949
John McCall755d8492011-04-12 00:42:48 +00009950 decl->setType(DestType);
9951 expr->setType(type);
9952 expr->setValueKind(valueKind);
9953 return S.Owned(expr);
John McCall379b5152011-04-11 07:02:50 +00009954}
9955
John McCall1de4d4e2011-04-07 08:22:57 +00009956/// Check a cast of an unknown-any type. We intentionally only
9957/// trigger this for C-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00009958ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
9959 Expr *castExpr, CastKind &castKind,
9960 ExprValueKind &VK, CXXCastPath &path) {
John McCall1de4d4e2011-04-07 08:22:57 +00009961 // Rewrite the casted expression from scratch.
John McCalla5fc4722011-04-09 22:50:59 +00009962 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
9963 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009964
John McCalla5fc4722011-04-09 22:50:59 +00009965 castExpr = result.take();
9966 VK = castExpr->getValueKind();
9967 castKind = CK_NoOp;
9968
9969 return castExpr;
John McCall1de4d4e2011-04-07 08:22:57 +00009970}
9971
9972static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
9973 Expr *orig = e;
John McCall379b5152011-04-11 07:02:50 +00009974 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +00009975 while (true) {
9976 e = e->IgnoreParenImpCasts();
John McCall379b5152011-04-11 07:02:50 +00009977 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall1de4d4e2011-04-07 08:22:57 +00009978 e = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +00009979 diagID = diag::err_uncasted_call_of_unknown_any;
9980 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00009981 break;
John McCall379b5152011-04-11 07:02:50 +00009982 }
John McCall1de4d4e2011-04-07 08:22:57 +00009983 }
9984
John McCall379b5152011-04-11 07:02:50 +00009985 SourceLocation loc;
9986 NamedDecl *d;
9987 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9988 loc = ref->getLocation();
9989 d = ref->getDecl();
9990 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
9991 loc = mem->getMemberLoc();
9992 d = mem->getMemberDecl();
9993 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
9994 diagID = diag::err_uncasted_call_of_unknown_any;
9995 loc = msg->getSelectorLoc();
9996 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +00009997 if (!d) {
9998 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
9999 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
10000 << orig->getSourceRange();
10001 return ExprError();
10002 }
John McCall379b5152011-04-11 07:02:50 +000010003 } else {
10004 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10005 << e->getSourceRange();
10006 return ExprError();
10007 }
10008
10009 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000010010
10011 // Never recoverable.
10012 return ExprError();
10013}
10014
John McCall2a984ca2010-10-12 00:20:44 +000010015/// Check for operands with placeholder types and complain if found.
10016/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000010017ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall1de4d4e2011-04-07 08:22:57 +000010018 // Placeholder types are always *exactly* the appropriate builtin type.
10019 QualType type = E->getType();
John McCall2a984ca2010-10-12 00:20:44 +000010020
John McCall1de4d4e2011-04-07 08:22:57 +000010021 // Overloaded expressions.
10022 if (type == Context.OverloadTy)
10023 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregordb2eae62011-03-16 19:16:25 +000010024 E->getSourceRange(),
John McCall1de4d4e2011-04-07 08:22:57 +000010025 QualType(),
10026 diag::err_ovl_unresolvable);
10027
John McCall864c0412011-04-26 20:42:42 +000010028 // Bound member functions.
10029 if (type == Context.BoundMemberTy) {
10030 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10031 << E->getSourceRange();
10032 return ExprError();
10033 }
10034
John McCall1de4d4e2011-04-07 08:22:57 +000010035 // Expressions of unknown type.
10036 if (type == Context.UnknownAnyTy)
10037 return diagnoseUnknownAnyExpr(*this, E);
10038
10039 assert(!type->isPlaceholderType());
10040 return Owned(E);
John McCall2a984ca2010-10-12 00:20:44 +000010041}
Richard Trieubb9b80c2011-04-21 21:44:26 +000010042
10043bool Sema::CheckCaseExpression(Expr *expr) {
10044 if (expr->isTypeDependent())
10045 return true;
10046 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
10047 return expr->getType()->isIntegralOrEnumerationType();
10048 return false;
10049}