blob: 67deb17ec7d9d75ba9a4baf95d8f8950db602a6d [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
572handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &lhsExpr,
573 ExprResult &rhsExpr, QualType lhs,
574 QualType rhs, bool isCompAssign) {
575 int order = S.Context.getFloatingTypeOrder(lhs, rhs);
576
577 if (order < 0) {
578 // _Complex float -> _Complex double
579 if (!isCompAssign)
580 lhsExpr = S.ImpCastExprToType(lhsExpr.take(), rhs,
581 CK_FloatingComplexCast);
582 return rhs;
583 }
584 if (order > 0)
585 // _Complex float -> _Complex double
586 rhsExpr = S.ImpCastExprToType(rhsExpr.take(), lhs,
587 CK_FloatingComplexCast);
588 return lhs;
589}
590
591/// \brief Converts otherExpr to complex float and promotes complexExpr if
592/// necessary. Helper function of UsualArithmeticConversions()
593static QualType handleOtherComplexFloatConversion(Sema &S,
594 ExprResult &complexExpr,
595 ExprResult &otherExpr,
596 QualType complexTy,
597 QualType otherTy,
598 bool convertComplexExpr,
599 bool convertOtherExpr) {
600 int order = S.Context.getFloatingTypeOrder(complexTy, otherTy);
601
602 // If just the complexExpr is complex, the otherExpr needs to be converted,
603 // and the complexExpr might need to be promoted.
604 if (order > 0) { // complexExpr is wider
605 // float -> _Complex double
606 if (convertOtherExpr) {
607 QualType fp = cast<ComplexType>(complexTy)->getElementType();
608 otherExpr = S.ImpCastExprToType(otherExpr.take(), fp, CK_FloatingCast);
609 otherExpr = S.ImpCastExprToType(otherExpr.take(), complexTy,
610 CK_FloatingRealToComplex);
611 }
612 return complexTy;
613 }
614
615 // otherTy is at least as wide. Find its corresponding complex type.
616 QualType result = (order == 0 ? complexTy :
617 S.Context.getComplexType(otherTy));
618
619 // double -> _Complex double
620 if (convertOtherExpr)
621 otherExpr = S.ImpCastExprToType(otherExpr.take(), result,
622 CK_FloatingRealToComplex);
623
624 // _Complex float -> _Complex double
625 if (convertComplexExpr && order < 0)
626 complexExpr = S.ImpCastExprToType(complexExpr.take(), result,
627 CK_FloatingComplexCast);
628
629 return result;
630}
631
632/// \brief Handle arithmetic conversion with complex types. Helper function of
633/// UsualArithmeticConversions()
634static QualType handleComplexFloatConversion(Sema &S, ExprResult &lhsExpr,
635 ExprResult &rhsExpr, QualType lhs,
636 QualType rhs, bool isCompAssign) {
637 // if we have an integer operand, the result is the complex type.
638 if (!handleIntegerToComplexFloatConversion(S, rhsExpr, lhsExpr, rhs, lhs,
639 /*skipCast*/false))
640 return lhs;
641 if (!handleIntegerToComplexFloatConversion(S, lhsExpr, rhsExpr, lhs, rhs,
642 /*skipCast*/isCompAssign))
643 return rhs;
644
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
656 bool LHSComplexFloat = lhs->isComplexType();
657 bool RHSComplexFloat = rhs->isComplexType();
658
659 // If both are complex, just cast to the more precise type.
660 if (LHSComplexFloat && RHSComplexFloat)
661 return handleComplexFloatToComplexFloatConverstion(S, lhsExpr, rhsExpr,
662 lhs, rhs, isCompAssign);
663
664 // If only one operand is complex, promote it if necessary and convert the
665 // other operand to complex.
666 if (LHSComplexFloat)
667 return handleOtherComplexFloatConversion(
668 S, lhsExpr, rhsExpr, lhs, rhs, /*convertComplexExpr*/!isCompAssign,
669 /*convertOtherExpr*/ true);
670
671 assert(RHSComplexFloat);
672 return handleOtherComplexFloatConversion(
673 S, rhsExpr, lhsExpr, rhs, lhs, /*convertComplexExpr*/true,
674 /*convertOtherExpr*/ !isCompAssign);
675}
676
677/// \brief Hande arithmetic conversion from integer to float. Helper function
678/// of UsualArithmeticConversions()
679static QualType handleIntToFloatConversion(Sema &S, ExprResult &floatExpr,
680 ExprResult &intExpr,
681 QualType floatTy, QualType intTy,
682 bool convertFloat, bool convertInt) {
683 if (intTy->isIntegerType()) {
684 if (convertInt)
685 // Convert intExpr to the lhs floating point type.
686 intExpr = S.ImpCastExprToType(intExpr.take(), floatTy,
687 CK_IntegralToFloating);
688 return floatTy;
689 }
690
691 // Convert both sides to the appropriate complex float.
692 assert(intTy->isComplexIntegerType());
693 QualType result = S.Context.getComplexType(floatTy);
694
695 // _Complex int -> _Complex float
696 if (convertInt)
697 intExpr = S.ImpCastExprToType(intExpr.take(), result,
698 CK_IntegralComplexToFloatingComplex);
699
700 // float -> _Complex float
701 if (convertFloat)
702 floatExpr = S.ImpCastExprToType(floatExpr.take(), result,
703 CK_FloatingRealToComplex);
704
705 return result;
706}
707
708/// \brief Handle arithmethic conversion with floating point types. Helper
709/// function of UsualArithmeticConversions()
710static QualType handleFloatConversion(Sema &S, ExprResult &lhsExpr,
711 ExprResult &rhsExpr, QualType lhs,
712 QualType rhs, bool isCompAssign) {
713 bool LHSFloat = lhs->isRealFloatingType();
714 bool RHSFloat = rhs->isRealFloatingType();
715
716 // If we have two real floating types, convert the smaller operand
717 // to the bigger result.
718 if (LHSFloat && RHSFloat) {
719 int order = S.Context.getFloatingTypeOrder(lhs, rhs);
720 if (order > 0) {
721 rhsExpr = S.ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
722 return lhs;
723 }
724
725 assert(order < 0 && "illegal float comparison");
726 if (!isCompAssign)
727 lhsExpr = S.ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
728 return rhs;
729 }
730
731 if (LHSFloat)
732 return handleIntToFloatConversion(S, lhsExpr, rhsExpr, lhs, rhs,
733 /*convertFloat=*/!isCompAssign,
734 /*convertInt=*/ true);
735 assert(RHSFloat);
736 return handleIntToFloatConversion(S, rhsExpr, lhsExpr, rhs, lhs,
737 /*convertInt=*/ true,
738 /*convertFloat=*/!isCompAssign);
739}
740
741/// \brief Handle conversions with GCC complex int extension. Helper function
742/// of UsualArithmeticConverions()
743// FIXME: if the operands are (int, _Complex long), we currently
744// don't promote the complex. Also, signedness?
745static QualType handleComplexIntConvsersion(Sema &S, ExprResult &lhsExpr,
746 ExprResult &rhsExpr, QualType lhs,
747 QualType rhs, bool isCompAssign) {
748 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
749 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
750
751 if (lhsComplexInt && rhsComplexInt) {
752 int order = S.Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
753 rhsComplexInt->getElementType());
754 assert(order && "inequal types with equal element ordering");
755 if (order > 0) {
756 // _Complex int -> _Complex long
757 rhsExpr = S.ImpCastExprToType(rhsExpr.take(), lhs,
758 CK_IntegralComplexCast);
759 return lhs;
760 }
761
762 if (!isCompAssign)
763 lhsExpr = S.ImpCastExprToType(lhsExpr.take(), rhs,
764 CK_IntegralComplexCast);
765 return rhs;
766 }
767
768 if (lhsComplexInt) {
769 // int -> _Complex int
770 rhsExpr = S.ImpCastExprToType(rhsExpr.take(), lhs,
771 CK_IntegralRealToComplex);
772 return lhs;
773 }
774
775 assert(rhsComplexInt);
776 // int -> _Complex int
777 if (!isCompAssign)
778 lhsExpr = S.ImpCastExprToType(lhsExpr.take(), rhs,
779 CK_IntegralRealToComplex);
780 return rhs;
781}
782
783/// \brief Handle integer arithmetic conversions. Helper function of
784/// UsualArithmeticConversions()
785static QualType handleIntegerConversion(Sema &S, ExprResult &lhsExpr,
786 ExprResult &rhsExpr, QualType lhs,
787 QualType rhs, bool isCompAssign) {
788 // The rules for this case are in C99 6.3.1.8
789 int order = S.Context.getIntegerTypeOrder(lhs, rhs);
790 bool lhsSigned = lhs->hasSignedIntegerRepresentation();
791 bool rhsSigned = rhs->hasSignedIntegerRepresentation();
792 if (lhsSigned == rhsSigned) {
793 // Same signedness; use the higher-ranked type
794 if (order >= 0) {
795 rhsExpr = S.ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
796 return lhs;
797 } else if (!isCompAssign)
798 lhsExpr = S.ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
799 return rhs;
800 } else if (order != (lhsSigned ? 1 : -1)) {
801 // The unsigned type has greater than or equal rank to the
802 // signed type, so use the unsigned type
803 if (rhsSigned) {
804 rhsExpr = S.ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
805 return lhs;
806 } else if (!isCompAssign)
807 lhsExpr = S.ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
808 return rhs;
809 } else if (S.Context.getIntWidth(lhs) != S.Context.getIntWidth(rhs)) {
810 // The two types are different widths; if we are here, that
811 // means the signed type is larger than the unsigned type, so
812 // use the signed type.
813 if (lhsSigned) {
814 rhsExpr = S.ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
815 return lhs;
816 } else if (!isCompAssign)
817 lhsExpr = S.ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
818 return rhs;
819 } else {
820 // The signed type is higher-ranked than the unsigned type,
821 // but isn't actually any bigger (like unsigned int and long
822 // on most 32-bit systems). Use the unsigned type corresponding
823 // to the signed type.
824 QualType result =
825 S.Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
826 rhsExpr = S.ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
827 if (!isCompAssign)
828 lhsExpr = S.ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
829 return result;
830 }
831}
832
Chris Lattnere7a2e912008-07-25 21:10:04 +0000833/// UsualArithmeticConversions - Performs various conversions that are common to
834/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000835/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000836/// responsible for emitting appropriate error diagnostics.
837/// FIXME: verify the conversion rules for "complex int" are consistent with
838/// GCC.
Richard Trieu67e29332011-08-02 04:35:43 +0000839QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr,
840 ExprResult &rhsExpr,
Chris Lattnere7a2e912008-07-25 21:10:04 +0000841 bool isCompAssign) {
John Wiegley429bb272011-04-08 18:41:53 +0000842 if (!isCompAssign) {
843 lhsExpr = UsualUnaryConversions(lhsExpr.take());
844 if (lhsExpr.isInvalid())
845 return QualType();
846 }
Eli Friedmanab3a8522009-03-28 01:22:36 +0000847
John Wiegley429bb272011-04-08 18:41:53 +0000848 rhsExpr = UsualUnaryConversions(rhsExpr.take());
849 if (rhsExpr.isInvalid())
850 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000851
Mike Stump1eb44332009-09-09 15:08:12 +0000852 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000853 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000854 QualType lhs =
John Wiegley429bb272011-04-08 18:41:53 +0000855 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000856 QualType rhs =
John Wiegley429bb272011-04-08 18:41:53 +0000857 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000858
859 // If both types are identical, no conversion is needed.
860 if (lhs == rhs)
861 return lhs;
862
863 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
864 // The caller can deal with this (e.g. pointer + int).
865 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
866 return lhs;
867
John McCallcf33b242010-11-13 08:17:45 +0000868 // Apply unary and bitfield promotions to the LHS's type.
869 QualType lhs_unpromoted = lhs;
870 if (lhs->isPromotableIntegerType())
871 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley429bb272011-04-08 18:41:53 +0000872 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +0000873 if (!LHSBitfieldPromoteTy.isNull())
874 lhs = LHSBitfieldPromoteTy;
John McCallcf33b242010-11-13 08:17:45 +0000875 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000876 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000877
John McCallcf33b242010-11-13 08:17:45 +0000878 // If both types are identical, no conversion is needed.
879 if (lhs == rhs)
880 return lhs;
881
882 // At this point, we have two different arithmetic types.
883
884 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu8289f492011-09-02 20:58:51 +0000885 if (lhs->isComplexType() || rhs->isComplexType())
886 return handleComplexFloatConversion(*this, lhsExpr, rhsExpr, lhs, rhs,
887 isCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000888
889 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu8289f492011-09-02 20:58:51 +0000890 if (lhs->isRealFloatingType() || rhs->isRealFloatingType())
891 return handleFloatConversion(*this, lhsExpr, rhsExpr, lhs, rhs,
892 isCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000893
894 // Handle GCC complex int extension.
Richard Trieu8289f492011-09-02 20:58:51 +0000895 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType())
896 return handleComplexIntConvsersion(*this, lhsExpr, rhsExpr, lhs, rhs,
897 isCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000898
899 // Finally, we have two differing integer types.
Richard Trieu8289f492011-09-02 20:58:51 +0000900 return handleIntegerConversion(*this, lhsExpr, rhsExpr, lhs, rhs,
901 isCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000902}
903
Chris Lattnere7a2e912008-07-25 21:10:04 +0000904//===----------------------------------------------------------------------===//
905// Semantic Analysis for various Expression Types
906//===----------------------------------------------------------------------===//
907
908
Peter Collingbournef111d932011-04-15 00:35:48 +0000909ExprResult
910Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
911 SourceLocation DefaultLoc,
912 SourceLocation RParenLoc,
913 Expr *ControllingExpr,
914 MultiTypeArg types,
915 MultiExprArg exprs) {
916 unsigned NumAssocs = types.size();
917 assert(NumAssocs == exprs.size());
918
919 ParsedType *ParsedTypes = types.release();
920 Expr **Exprs = exprs.release();
921
922 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
923 for (unsigned i = 0; i < NumAssocs; ++i) {
924 if (ParsedTypes[i])
925 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
926 else
927 Types[i] = 0;
928 }
929
930 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
931 ControllingExpr, Types, Exprs,
932 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +0000933 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +0000934 return ER;
935}
936
937ExprResult
938Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
939 SourceLocation DefaultLoc,
940 SourceLocation RParenLoc,
941 Expr *ControllingExpr,
942 TypeSourceInfo **Types,
943 Expr **Exprs,
944 unsigned NumAssocs) {
945 bool TypeErrorFound = false,
946 IsResultDependent = ControllingExpr->isTypeDependent(),
947 ContainsUnexpandedParameterPack
948 = ControllingExpr->containsUnexpandedParameterPack();
949
950 for (unsigned i = 0; i < NumAssocs; ++i) {
951 if (Exprs[i]->containsUnexpandedParameterPack())
952 ContainsUnexpandedParameterPack = true;
953
954 if (Types[i]) {
955 if (Types[i]->getType()->containsUnexpandedParameterPack())
956 ContainsUnexpandedParameterPack = true;
957
958 if (Types[i]->getType()->isDependentType()) {
959 IsResultDependent = true;
960 } else {
961 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
962 // complete object type other than a variably modified type."
963 unsigned D = 0;
964 if (Types[i]->getType()->isIncompleteType())
965 D = diag::err_assoc_type_incomplete;
966 else if (!Types[i]->getType()->isObjectType())
967 D = diag::err_assoc_type_nonobject;
968 else if (Types[i]->getType()->isVariablyModifiedType())
969 D = diag::err_assoc_type_variably_modified;
970
971 if (D != 0) {
972 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
973 << Types[i]->getTypeLoc().getSourceRange()
974 << Types[i]->getType();
975 TypeErrorFound = true;
976 }
977
978 // C1X 6.5.1.1p2 "No two generic associations in the same generic
979 // selection shall specify compatible types."
980 for (unsigned j = i+1; j < NumAssocs; ++j)
981 if (Types[j] && !Types[j]->getType()->isDependentType() &&
982 Context.typesAreCompatible(Types[i]->getType(),
983 Types[j]->getType())) {
984 Diag(Types[j]->getTypeLoc().getBeginLoc(),
985 diag::err_assoc_compatible_types)
986 << Types[j]->getTypeLoc().getSourceRange()
987 << Types[j]->getType()
988 << Types[i]->getType();
989 Diag(Types[i]->getTypeLoc().getBeginLoc(),
990 diag::note_compat_assoc)
991 << Types[i]->getTypeLoc().getSourceRange()
992 << Types[i]->getType();
993 TypeErrorFound = true;
994 }
995 }
996 }
997 }
998 if (TypeErrorFound)
999 return ExprError();
1000
1001 // If we determined that the generic selection is result-dependent, don't
1002 // try to compute the result expression.
1003 if (IsResultDependent)
1004 return Owned(new (Context) GenericSelectionExpr(
1005 Context, KeyLoc, ControllingExpr,
1006 Types, Exprs, NumAssocs, DefaultLoc,
1007 RParenLoc, ContainsUnexpandedParameterPack));
1008
Chris Lattner5f9e2722011-07-23 10:55:15 +00001009 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +00001010 unsigned DefaultIndex = -1U;
1011 for (unsigned i = 0; i < NumAssocs; ++i) {
1012 if (!Types[i])
1013 DefaultIndex = i;
1014 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1015 Types[i]->getType()))
1016 CompatIndices.push_back(i);
1017 }
1018
1019 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
1020 // type compatible with at most one of the types named in its generic
1021 // association list."
1022 if (CompatIndices.size() > 1) {
1023 // We strip parens here because the controlling expression is typically
1024 // parenthesized in macro definitions.
1025 ControllingExpr = ControllingExpr->IgnoreParens();
1026 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1027 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1028 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001029 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001030 E = CompatIndices.end(); I != E; ++I) {
1031 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1032 diag::note_compat_assoc)
1033 << Types[*I]->getTypeLoc().getSourceRange()
1034 << Types[*I]->getType();
1035 }
1036 return ExprError();
1037 }
1038
1039 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
1040 // its controlling expression shall have type compatible with exactly one of
1041 // the types named in its generic association list."
1042 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1043 // We strip parens here because the controlling expression is typically
1044 // parenthesized in macro definitions.
1045 ControllingExpr = ControllingExpr->IgnoreParens();
1046 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1047 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1048 return ExprError();
1049 }
1050
1051 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1052 // type name that is compatible with the type of the controlling expression,
1053 // then the result expression of the generic selection is the expression
1054 // in that generic association. Otherwise, the result expression of the
1055 // generic selection is the expression in the default generic association."
1056 unsigned ResultIndex =
1057 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1058
1059 return Owned(new (Context) GenericSelectionExpr(
1060 Context, KeyLoc, ControllingExpr,
1061 Types, Exprs, NumAssocs, DefaultLoc,
1062 RParenLoc, ContainsUnexpandedParameterPack,
1063 ResultIndex));
1064}
1065
Steve Narofff69936d2007-09-16 03:34:24 +00001066/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001067/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1068/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1069/// multiple tokens. However, the common case is that StringToks points to one
1070/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001071///
John McCall60d7b3a2010-08-24 06:29:42 +00001072ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +00001073Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001074 assert(NumStringToks && "Must have at least one string!");
1075
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001076 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001077 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001078 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001079
Chris Lattner5f9e2722011-07-23 10:55:15 +00001080 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001081 for (unsigned i = 0; i != NumStringToks; ++i)
1082 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001083
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001084 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001085 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001086 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001087 else if (Literal.isUTF16())
1088 StrTy = Context.Char16Ty;
1089 else if (Literal.isUTF32())
1090 StrTy = Context.Char32Ty;
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001091 else if (Literal.Pascal)
1092 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001093
Douglas Gregor5cee1192011-07-27 05:40:30 +00001094 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1095 if (Literal.isWide())
1096 Kind = StringLiteral::Wide;
1097 else if (Literal.isUTF8())
1098 Kind = StringLiteral::UTF8;
1099 else if (Literal.isUTF16())
1100 Kind = StringLiteral::UTF16;
1101 else if (Literal.isUTF32())
1102 Kind = StringLiteral::UTF32;
1103
Douglas Gregor77a52232008-09-12 00:47:35 +00001104 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +00001105 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001106 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001107
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001108 // Get an array type for the string, according to C99 6.4.5. This includes
1109 // the nul terminator character as well as the string length for pascal
1110 // strings.
1111 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001112 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001113 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001114
Reid Spencer5f016e22007-07-11 17:01:13 +00001115 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +00001116 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001117 Kind, Literal.Pascal, StrTy,
Sean Hunt6cf75022010-08-30 17:47:05 +00001118 &StringTokLocs[0],
1119 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001120}
1121
John McCall469a1eb2011-02-02 13:00:07 +00001122enum CaptureResult {
1123 /// No capture is required.
1124 CR_NoCapture,
1125
1126 /// A capture is required.
1127 CR_Capture,
1128
John McCall6b5a61b2011-02-07 10:33:21 +00001129 /// A by-ref capture is required.
1130 CR_CaptureByRef,
1131
John McCall469a1eb2011-02-02 13:00:07 +00001132 /// An error occurred when trying to capture the given variable.
1133 CR_Error
1134};
1135
1136/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +00001137///
John McCall469a1eb2011-02-02 13:00:07 +00001138/// \param var - the variable referenced
1139/// \param DC - the context which we couldn't capture through
1140static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +00001141diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001142 VarDecl *var, DeclContext *DC) {
1143 switch (S.ExprEvalContexts.back().Context) {
1144 case Sema::Unevaluated:
1145 // The argument will never be evaluated, so don't complain.
1146 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +00001147
John McCall469a1eb2011-02-02 13:00:07 +00001148 case Sema::PotentiallyEvaluated:
1149 case Sema::PotentiallyEvaluatedIfUsed:
1150 break;
Chris Lattner639e2d32008-10-20 05:16:36 +00001151
John McCall469a1eb2011-02-02 13:00:07 +00001152 case Sema::PotentiallyPotentiallyEvaluated:
1153 // FIXME: delay these!
1154 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +00001155 }
Mike Stump1eb44332009-09-09 15:08:12 +00001156
John McCall469a1eb2011-02-02 13:00:07 +00001157 // Don't diagnose about capture if we're not actually in code right
1158 // now; in general, there are more appropriate places that will
1159 // diagnose this.
1160 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1161
John McCall4f38f412011-03-22 23:15:50 +00001162 // Certain madnesses can happen with parameter declarations, which
1163 // we want to ignore.
1164 if (isa<ParmVarDecl>(var)) {
1165 // - If the parameter still belongs to the translation unit, then
1166 // we're actually just using one parameter in the declaration of
1167 // the next. This is useful in e.g. VLAs.
1168 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1169 return CR_NoCapture;
1170
1171 // - This particular madness can happen in ill-formed default
1172 // arguments; claim it's okay and let downstream code handle it.
1173 if (S.CurContext == var->getDeclContext()->getParent())
1174 return CR_NoCapture;
1175 }
John McCall469a1eb2011-02-02 13:00:07 +00001176
1177 DeclarationName functionName;
1178 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1179 functionName = fn->getDeclName();
1180 // FIXME: variable from enclosing block that we couldn't capture from!
1181
1182 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1183 << var->getIdentifier() << functionName;
1184 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1185 << var->getIdentifier();
1186
1187 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001188}
1189
John McCall6b5a61b2011-02-07 10:33:21 +00001190/// There is a well-formed capture at a particular scope level;
1191/// propagate it through all the nested blocks.
1192static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1193 const BlockDecl::Capture &capture) {
1194 VarDecl *var = capture.getVariable();
1195
1196 // Update all the inner blocks with the capture information.
1197 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1198 i != e; ++i) {
1199 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1200 innerBlock->Captures.push_back(
1201 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1202 /*nested*/ true, capture.getCopyExpr()));
1203 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1204 }
1205
1206 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1207}
1208
1209/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +00001210/// given value in the current context requires a variable capture.
1211///
1212/// This also keeps the captures set in the BlockScopeInfo records
1213/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +00001214static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001215 ValueDecl *value) {
1216 // Only variables ever require capture.
1217 VarDecl *var = dyn_cast<VarDecl>(value);
John McCall76a40212011-02-09 01:13:10 +00001218 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +00001219
1220 // Fast path: variables from the current context never require capture.
1221 DeclContext *DC = S.CurContext;
1222 if (var->getDeclContext() == DC) return CR_NoCapture;
1223
1224 // Only variables with local storage require capture.
1225 // FIXME: What about 'const' variables in C++?
1226 if (!var->hasLocalStorage()) return CR_NoCapture;
1227
1228 // Otherwise, we need to capture.
1229
1230 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +00001231 do {
1232 // Only blocks (and eventually C++0x closures) can capture; other
1233 // scopes don't work.
1234 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +00001235 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +00001236
1237 BlockScopeInfo *blockScope =
1238 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1239 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1240
John McCall6b5a61b2011-02-07 10:33:21 +00001241 // Check whether we've already captured it in this block. If so,
1242 // we're done.
1243 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1244 return propagateCapture(S, functionScopesIndex,
1245 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +00001246
1247 functionScopesIndex--;
1248 DC = cast<BlockDecl>(DC)->getDeclContext();
1249 } while (var->getDeclContext() != DC);
1250
John McCall6b5a61b2011-02-07 10:33:21 +00001251 // Okay, we descended all the way to the block that defines the variable.
1252 // Actually try to capture it.
1253 QualType type = var->getType();
1254
1255 // Prohibit variably-modified types.
1256 if (type->isVariablyModifiedType()) {
1257 S.Diag(loc, diag::err_ref_vm_type);
1258 S.Diag(var->getLocation(), diag::note_declared_at);
1259 return CR_Error;
1260 }
1261
1262 // Prohibit arrays, even in __block variables, but not references to
1263 // them.
1264 if (type->isArrayType()) {
1265 S.Diag(loc, diag::err_ref_array_type);
1266 S.Diag(var->getLocation(), diag::note_declared_at);
1267 return CR_Error;
1268 }
1269
1270 S.MarkDeclarationReferenced(loc, var);
1271
1272 // The BlocksAttr indicates the variable is bound by-reference.
1273 bool byRef = var->hasAttr<BlocksAttr>();
1274
1275 // Build a copy expression.
1276 Expr *copyExpr = 0;
John McCall642a75f2011-04-28 02:15:35 +00001277 const RecordType *rtype;
1278 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1279 (rtype = type->getAs<RecordType>())) {
1280
1281 // The capture logic needs the destructor, so make sure we mark it.
1282 // Usually this is unnecessary because most local variables have
1283 // their destructors marked at declaration time, but parameters are
1284 // an exception because it's technically only the call site that
1285 // actually requires the destructor.
1286 if (isa<ParmVarDecl>(var))
1287 S.FinalizeVarWithDestructor(var, rtype);
1288
John McCall6b5a61b2011-02-07 10:33:21 +00001289 // According to the blocks spec, the capture of a variable from
1290 // the stack requires a const copy constructor. This is not true
1291 // of the copy/move done to move a __block variable to the heap.
1292 type.addConst();
1293
1294 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1295 ExprResult result =
1296 S.PerformCopyInitialization(
1297 InitializedEntity::InitializeBlock(var->getLocation(),
1298 type, false),
1299 loc, S.Owned(declRef));
1300
1301 // Build a full-expression copy expression if initialization
1302 // succeeded and used a non-trivial constructor. Recover from
1303 // errors by pretending that the copy isn't necessary.
1304 if (!result.isInvalid() &&
1305 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1306 result = S.MaybeCreateExprWithCleanups(result);
1307 copyExpr = result.take();
1308 }
1309 }
1310
1311 // We're currently at the declarer; go back to the closure.
1312 functionScopesIndex++;
1313 BlockScopeInfo *blockScope =
1314 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1315
1316 // Build a valid capture in this scope.
1317 blockScope->Captures.push_back(
1318 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1319 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1320
1321 // Propagate that to inner captures if necessary.
1322 return propagateCapture(S, functionScopesIndex,
1323 blockScope->Captures.back());
1324}
1325
1326static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1327 const DeclarationNameInfo &NameInfo,
1328 bool byRef) {
1329 assert(isa<VarDecl>(vd) && "capturing non-variable");
1330
1331 VarDecl *var = cast<VarDecl>(vd);
1332 assert(var->hasLocalStorage() && "capturing non-local");
1333 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1334
1335 QualType exprType = var->getType().getNonReferenceType();
1336
1337 BlockDeclRefExpr *BDRE;
1338 if (!byRef) {
1339 // The variable will be bound by copy; make it const within the
1340 // closure, but record that this was done in the expression.
1341 bool constAdded = !exprType.isConstQualified();
1342 exprType.addConst();
1343
1344 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1345 NameInfo.getLoc(), false,
1346 constAdded);
1347 } else {
1348 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1349 NameInfo.getLoc(), true);
1350 }
1351
1352 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +00001353}
Chris Lattner639e2d32008-10-20 05:16:36 +00001354
John McCall60d7b3a2010-08-24 06:29:42 +00001355ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001356Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001357 SourceLocation Loc,
1358 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001359 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001360 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001361}
1362
John McCall76a40212011-02-09 01:13:10 +00001363/// BuildDeclRefExpr - Build an expression that references a
1364/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001365ExprResult
John McCall76a40212011-02-09 01:13:10 +00001366Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001367 const DeclarationNameInfo &NameInfo,
1368 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001369 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +00001370
John McCall7eb0a9e2010-11-24 05:12:34 +00001371 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00001372 SS? SS->getWithLocInContext(Context)
1373 : NestedNameSpecifierLoc(),
John McCall7eb0a9e2010-11-24 05:12:34 +00001374 D, NameInfo, Ty, VK);
1375
1376 // Just in case we're building an illegal pointer-to-member.
1377 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1378 E->setObjectKind(OK_BitField);
1379
1380 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001381}
1382
Abramo Bagnara25777432010-08-11 22:01:17 +00001383/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001384/// possibly a list of template arguments.
1385///
1386/// If this produces template arguments, it is permitted to call
1387/// DecomposeTemplateName.
1388///
1389/// This actually loses a lot of source location information for
1390/// non-standard name kinds; we should consider preserving that in
1391/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001392void
1393Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1394 TemplateArgumentListInfo &Buffer,
1395 DeclarationNameInfo &NameInfo,
1396 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001397 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1398 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1399 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1400
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001401 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall129e2df2009-11-30 22:42:35 +00001402 Id.TemplateId->getTemplateArgs(),
1403 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001404 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001405 TemplateArgsPtr.release();
1406
John McCall2b5289b2010-08-23 07:28:44 +00001407 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001408 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001409 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001410 TemplateArgs = &Buffer;
1411 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001412 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001413 TemplateArgs = 0;
1414 }
1415}
1416
John McCall578b69b2009-12-16 08:11:27 +00001417/// Diagnose an empty lookup.
1418///
1419/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001420bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001421 CorrectTypoContext CTC,
1422 TemplateArgumentListInfo *ExplicitTemplateArgs,
1423 Expr **Args, unsigned NumArgs) {
John McCall578b69b2009-12-16 08:11:27 +00001424 DeclarationName Name = R.getLookupName();
1425
John McCall578b69b2009-12-16 08:11:27 +00001426 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001427 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001428 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1429 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001430 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001431 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001432 diagnostic_suggest = diag::err_undeclared_use_suggest;
1433 }
John McCall578b69b2009-12-16 08:11:27 +00001434
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001435 // If the original lookup was an unqualified lookup, fake an
1436 // unqualified lookup. This is useful when (for example) the
1437 // original lookup would not have found something because it was a
1438 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001439 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001440 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001441 if (isa<CXXRecordDecl>(DC)) {
1442 LookupQualifiedName(R, DC);
1443
1444 if (!R.empty()) {
1445 // Don't give errors about ambiguities in this lookup.
1446 R.suppressDiagnostics();
1447
1448 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1449 bool isInstance = CurMethod &&
1450 CurMethod->isInstance() &&
1451 DC == CurMethod->getParent();
1452
1453 // Give a code modification hint to insert 'this->'.
1454 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1455 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001456 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001457 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1458 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001459 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001460 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001461 if (DepMethod) {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001462 Diag(R.getNameLoc(), diagnostic) << Name
1463 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1464 QualType DepThisType = DepMethod->getThisType(Context);
1465 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1466 R.getNameLoc(), DepThisType, false);
1467 TemplateArgumentListInfo TList;
1468 if (ULE->hasExplicitTemplateArgs())
1469 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001470
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001471 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00001472 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001473 CXXDependentScopeMemberExpr *DepExpr =
1474 CXXDependentScopeMemberExpr::Create(
1475 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001476 SS.getWithLocInContext(Context), NULL,
Francois Pichetf7400122011-09-04 23:00:48 +00001477 R.getLookupNameInfo(),
1478 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001479 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001480 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001481 // FIXME: we should be able to handle this case too. It is correct
1482 // to add this-> here. This is a workaround for PR7947.
1483 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001484 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001485 } else {
John McCall578b69b2009-12-16 08:11:27 +00001486 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001487 }
John McCall578b69b2009-12-16 08:11:27 +00001488
1489 // Do we really want to note all of these?
1490 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1491 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1492
1493 // Tell the callee to try to recover.
1494 return false;
1495 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001496
1497 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001498 }
1499 }
1500
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001501 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001502 TypoCorrection Corrected;
1503 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1504 S, &SS, NULL, false, CTC))) {
1505 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1506 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1507 R.setLookupName(Corrected.getCorrection());
1508
Hans Wennborg701d1e72011-07-12 08:45:31 +00001509 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001510 if (Corrected.isOverloaded()) {
1511 OverloadCandidateSet OCS(R.getNameLoc());
1512 OverloadCandidateSet::iterator Best;
1513 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1514 CDEnd = Corrected.end();
1515 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001516 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001517 dyn_cast<FunctionTemplateDecl>(*CD))
1518 AddTemplateOverloadCandidate(
1519 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1520 Args, NumArgs, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001521 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1522 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1523 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1524 Args, NumArgs, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001525 }
1526 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1527 case OR_Success:
1528 ND = Best->Function;
1529 break;
1530 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001531 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001532 }
1533 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001534 R.addDecl(ND);
1535 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001536 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001537 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1538 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001539 else
1540 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001541 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001542 << SS.getRange()
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001543 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1544 if (ND)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001545 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001546 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001547
1548 // Tell the callee to try to recover.
1549 return false;
1550 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001551
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001552 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001553 // FIXME: If we ended up with a typo for a type name or
1554 // Objective-C class name, we're in trouble because the parser
1555 // is in the wrong place to recover. Suggest the typo
1556 // correction, but don't make it a fix-it since we're not going
1557 // to recover well anyway.
1558 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001559 Diag(R.getNameLoc(), diagnostic_suggest)
1560 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001561 else
1562 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001563 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001564 << SS.getRange();
1565
1566 // Don't try to recover; it won't work.
1567 return true;
1568 }
1569 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001570 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001571 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001572 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001573 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001574 else
Douglas Gregord203a162010-01-01 00:15:04 +00001575 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001576 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001577 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001578 return true;
1579 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001580 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001581 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001582
1583 // Emit a special diagnostic for failed member lookups.
1584 // FIXME: computing the declaration context might fail here (?)
1585 if (!SS.isEmpty()) {
1586 Diag(R.getNameLoc(), diag::err_no_member)
1587 << Name << computeDeclContext(SS, false)
1588 << SS.getRange();
1589 return true;
1590 }
1591
John McCall578b69b2009-12-16 08:11:27 +00001592 // Give up, we can't recover.
1593 Diag(R.getNameLoc(), diagnostic) << Name;
1594 return true;
1595}
1596
John McCall60d7b3a2010-08-24 06:29:42 +00001597ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001598 CXXScopeSpec &SS,
1599 UnqualifiedId &Id,
1600 bool HasTrailingLParen,
1601 bool isAddressOfOperand) {
John McCallf7a1a742009-11-24 19:00:30 +00001602 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1603 "cannot be direct & operand and have a trailing lparen");
1604
1605 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001606 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001607
John McCall129e2df2009-11-30 22:42:35 +00001608 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001609
1610 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001611 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001612 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001613 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001614
Abramo Bagnara25777432010-08-11 22:01:17 +00001615 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001616 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001617 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001618
John McCallf7a1a742009-11-24 19:00:30 +00001619 // C++ [temp.dep.expr]p3:
1620 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001621 // -- an identifier that was declared with a dependent type,
1622 // (note: handled after lookup)
1623 // -- a template-id that is dependent,
1624 // (note: handled in BuildTemplateIdExpr)
1625 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001626 // -- a nested-name-specifier that contains a class-name that
1627 // names a dependent type.
1628 // Determine whether this is a member of an unknown specialization;
1629 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001630 bool DependentID = false;
1631 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1632 Name.getCXXNameType()->isDependentType()) {
1633 DependentID = true;
1634 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001635 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001636 if (RequireCompleteDeclContext(SS, DC))
1637 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001638 } else {
1639 DependentID = true;
1640 }
1641 }
1642
Chris Lattner337e5502011-02-18 01:27:55 +00001643 if (DependentID)
Abramo Bagnara25777432010-08-11 22:01:17 +00001644 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001645 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001646
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001647 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001648 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001649 LookupResult R(*this, NameInfo,
1650 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1651 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001652 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001653 // Lookup the template name again to correctly establish the context in
1654 // which it was found. This is really unfortunate as we already did the
1655 // lookup to determine that it was a template name in the first place. If
1656 // this becomes a performance hit, we can work harder to preserve those
1657 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001658 bool MemberOfUnknownSpecialization;
1659 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1660 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001661
1662 if (MemberOfUnknownSpecialization ||
1663 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1664 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1665 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001666 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001667 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001668 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001669
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001670 // If the result might be in a dependent base class, this is a dependent
1671 // id-expression.
1672 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1673 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1674 TemplateArgs);
1675
John McCallf7a1a742009-11-24 19:00:30 +00001676 // If this reference is in an Objective-C method, then we need to do
1677 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001678 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001679 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001680 if (E.isInvalid())
1681 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001682
Chris Lattner337e5502011-02-18 01:27:55 +00001683 if (Expr *Ex = E.takeAs<Expr>())
1684 return Owned(Ex);
1685
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001686 // for further use, this must be set to false if in class method.
1687 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001688 }
Chris Lattner8a934232008-03-31 00:36:02 +00001689 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001690
John McCallf7a1a742009-11-24 19:00:30 +00001691 if (R.isAmbiguous())
1692 return ExprError();
1693
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001694 // Determine whether this name might be a candidate for
1695 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001696 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001697
John McCallf7a1a742009-11-24 19:00:30 +00001698 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001699 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001700 // in C90, extension in C99, forbidden in C++).
1701 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1702 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1703 if (D) R.addDecl(D);
1704 }
1705
1706 // If this name wasn't predeclared and if this is not a function
1707 // call, diagnose the problem.
1708 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001709 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001710 return ExprError();
1711
1712 assert(!R.empty() &&
1713 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001714
1715 // If we found an Objective-C instance variable, let
1716 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001717 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001718 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1719 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001720 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001721 assert(E.isInvalid() || E.get());
1722 return move(E);
1723 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001724 }
1725 }
Mike Stump1eb44332009-09-09 15:08:12 +00001726
John McCallf7a1a742009-11-24 19:00:30 +00001727 // This is guaranteed from this point on.
1728 assert(!R.empty() || ADL);
1729
John McCallaa81e162009-12-01 22:10:20 +00001730 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001731 // C++ [class.mfct.non-static]p3:
1732 // When an id-expression that is not part of a class member access
1733 // syntax and not used to form a pointer to member is used in the
1734 // body of a non-static member function of class X, if name lookup
1735 // resolves the name in the id-expression to a non-static non-type
1736 // member of some class C, the id-expression is transformed into a
1737 // class member access expression using (*this) as the
1738 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001739 //
1740 // But we don't actually need to do this for '&' operands if R
1741 // resolved to a function or overloaded function set, because the
1742 // expression is ill-formed if it actually works out to be a
1743 // non-static member function:
1744 //
1745 // C++ [expr.ref]p4:
1746 // Otherwise, if E1.E2 refers to a non-static member function. . .
1747 // [t]he expression can be used only as the left-hand operand of a
1748 // member function call.
1749 //
1750 // There are other safeguards against such uses, but it's important
1751 // to get this right here so that we don't end up making a
1752 // spuriously dependent expression if we're inside a dependent
1753 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001754 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001755 bool MightBeImplicitMember;
1756 if (!isAddressOfOperand)
1757 MightBeImplicitMember = true;
1758 else if (!SS.isEmpty())
1759 MightBeImplicitMember = false;
1760 else if (R.isOverloadedResult())
1761 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001762 else if (R.isUnresolvableResult())
1763 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001764 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001765 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1766 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001767
1768 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001769 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001770 }
1771
John McCallf7a1a742009-11-24 19:00:30 +00001772 if (TemplateArgs)
1773 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001774
John McCallf7a1a742009-11-24 19:00:30 +00001775 return BuildDeclarationNameExpr(SS, R, ADL);
1776}
1777
John McCall129e2df2009-11-30 22:42:35 +00001778/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1779/// declaration name, generally during template instantiation.
1780/// There's a large number of things which don't need to be done along
1781/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001782ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001783Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001784 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001785 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001786 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001787 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001788
John McCall77bb1aa2010-05-01 00:40:08 +00001789 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001790 return ExprError();
1791
Abramo Bagnara25777432010-08-11 22:01:17 +00001792 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001793 LookupQualifiedName(R, DC);
1794
1795 if (R.isAmbiguous())
1796 return ExprError();
1797
1798 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001799 Diag(NameInfo.getLoc(), diag::err_no_member)
1800 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001801 return ExprError();
1802 }
1803
1804 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1805}
1806
1807/// LookupInObjCMethod - The parser has read a name in, and Sema has
1808/// detected that we're currently inside an ObjC method. Perform some
1809/// additional lookup.
1810///
1811/// Ideally, most of this would be done by lookup, but there's
1812/// actually quite a lot of extra work involved.
1813///
1814/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001815ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001816Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001817 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001818 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001819 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001820
John McCallf7a1a742009-11-24 19:00:30 +00001821 // There are two cases to handle here. 1) scoped lookup could have failed,
1822 // in which case we should look for an ivar. 2) scoped lookup could have
1823 // found a decl, but that decl is outside the current instance method (i.e.
1824 // a global variable). In these two cases, we do a lookup for an ivar with
1825 // this name, if the lookup sucedes, we replace it our current decl.
1826
1827 // If we're in a class method, we don't normally want to look for
1828 // ivars. But if we don't find anything else, and there's an
1829 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001830 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001831
1832 bool LookForIvars;
1833 if (Lookup.empty())
1834 LookForIvars = true;
1835 else if (IsClassMethod)
1836 LookForIvars = false;
1837 else
1838 LookForIvars = (Lookup.isSingleResult() &&
1839 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001840 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001841 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001842 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001843 ObjCInterfaceDecl *ClassDeclared;
1844 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1845 // Diagnose using an ivar in a class method.
1846 if (IsClassMethod)
1847 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1848 << IV->getDeclName());
1849
1850 // If we're referencing an invalid decl, just return this as a silent
1851 // error node. The error diagnostic was already emitted on the decl.
1852 if (IV->isInvalidDecl())
1853 return ExprError();
1854
1855 // Check if referencing a field with __attribute__((deprecated)).
1856 if (DiagnoseUseOfDecl(IV, Loc))
1857 return ExprError();
1858
1859 // Diagnose the use of an ivar outside of the declaring class.
1860 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1861 ClassDeclared != IFace)
1862 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1863
1864 // FIXME: This should use a new expr for a direct reference, don't
1865 // turn this into Self->ivar, just return a BareIVarExpr or something.
1866 IdentifierInfo &II = Context.Idents.get("self");
1867 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001868 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001869 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00001870 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00001871 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001872 SelfName, false, false);
1873 if (SelfExpr.isInvalid())
1874 return ExprError();
1875
John Wiegley429bb272011-04-08 18:41:53 +00001876 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1877 if (SelfExpr.isInvalid())
1878 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001879
John McCallf7a1a742009-11-24 19:00:30 +00001880 MarkDeclarationReferenced(Loc, IV);
1881 return Owned(new (Context)
1882 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00001883 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001884 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001885 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001886 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001887 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001888 ObjCInterfaceDecl *ClassDeclared;
1889 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1890 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1891 IFace == ClassDeclared)
1892 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1893 }
1894 }
1895
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001896 if (Lookup.empty() && II && AllowBuiltinCreation) {
1897 // FIXME. Consolidate this with similar code in LookupName.
1898 if (unsigned BuiltinID = II->getBuiltinID()) {
1899 if (!(getLangOptions().CPlusPlus &&
1900 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1901 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1902 S, Lookup.isForRedeclaration(),
1903 Lookup.getNameLoc());
1904 if (D) Lookup.addDecl(D);
1905 }
1906 }
1907 }
John McCallf7a1a742009-11-24 19:00:30 +00001908 // Sentinel value saying that we didn't do anything special.
1909 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001910}
John McCallba135432009-11-21 08:51:07 +00001911
John McCall6bb80172010-03-30 21:47:33 +00001912/// \brief Cast a base object to a member's actual type.
1913///
1914/// Logically this happens in three phases:
1915///
1916/// * First we cast from the base type to the naming class.
1917/// The naming class is the class into which we were looking
1918/// when we found the member; it's the qualifier type if a
1919/// qualifier was provided, and otherwise it's the base type.
1920///
1921/// * Next we cast from the naming class to the declaring class.
1922/// If the member we found was brought into a class's scope by
1923/// a using declaration, this is that class; otherwise it's
1924/// the class declaring the member.
1925///
1926/// * Finally we cast from the declaring class to the "true"
1927/// declaring class of the member. This conversion does not
1928/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00001929ExprResult
1930Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001931 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001932 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001933 NamedDecl *Member) {
1934 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1935 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00001936 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001937
Douglas Gregor5fccd362010-03-03 23:55:11 +00001938 QualType DestRecordType;
1939 QualType DestType;
1940 QualType FromRecordType;
1941 QualType FromType = From->getType();
1942 bool PointerConversions = false;
1943 if (isa<FieldDecl>(Member)) {
1944 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001945
Douglas Gregor5fccd362010-03-03 23:55:11 +00001946 if (FromType->getAs<PointerType>()) {
1947 DestType = Context.getPointerType(DestRecordType);
1948 FromRecordType = FromType->getPointeeType();
1949 PointerConversions = true;
1950 } else {
1951 DestType = DestRecordType;
1952 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001953 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001954 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1955 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00001956 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001957
Douglas Gregor5fccd362010-03-03 23:55:11 +00001958 DestType = Method->getThisType(Context);
1959 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001960
Douglas Gregor5fccd362010-03-03 23:55:11 +00001961 if (FromType->getAs<PointerType>()) {
1962 FromRecordType = FromType->getPointeeType();
1963 PointerConversions = true;
1964 } else {
1965 FromRecordType = FromType;
1966 DestType = DestRecordType;
1967 }
1968 } else {
1969 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00001970 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00001971 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001972
Douglas Gregor5fccd362010-03-03 23:55:11 +00001973 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00001974 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001975
Douglas Gregor5fccd362010-03-03 23:55:11 +00001976 // If the unqualified types are the same, no conversion is necessary.
1977 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00001978 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001979
John McCall6bb80172010-03-30 21:47:33 +00001980 SourceRange FromRange = From->getSourceRange();
1981 SourceLocation FromLoc = FromRange.getBegin();
1982
John McCall5baba9d2010-08-25 10:28:54 +00001983 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00001984
Douglas Gregor5fccd362010-03-03 23:55:11 +00001985 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001986 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00001987 // class name.
1988 //
1989 // If the member was a qualified name and the qualified referred to a
1990 // specific base subobject type, we'll cast to that intermediate type
1991 // first and then to the object in which the member is declared. That allows
1992 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1993 //
1994 // class Base { public: int x; };
1995 // class Derived1 : public Base { };
1996 // class Derived2 : public Base { };
1997 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1998 //
1999 // void VeryDerived::f() {
2000 // x = 17; // error: ambiguous base subobjects
2001 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2002 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002003 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002004 QualType QType = QualType(Qualifier->getAsType(), 0);
2005 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2006 assert(QType->isRecordType() && "lookup done with non-record type");
2007
2008 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2009
2010 // In C++98, the qualifier type doesn't actually have to be a base
2011 // type of the object type, in which case we just ignore it.
2012 // Otherwise build the appropriate casts.
2013 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002014 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002015 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002016 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002017 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002018
Douglas Gregor5fccd362010-03-03 23:55:11 +00002019 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002020 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002021 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2022 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002023
2024 FromType = QType;
2025 FromRecordType = QRecordType;
2026
2027 // If the qualifier type was the same as the destination type,
2028 // we're done.
2029 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002030 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002031 }
2032 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002033
John McCall6bb80172010-03-30 21:47:33 +00002034 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002035
John McCall6bb80172010-03-30 21:47:33 +00002036 // If we actually found the member through a using declaration, cast
2037 // down to the using declaration's type.
2038 //
2039 // Pointer equality is fine here because only one declaration of a
2040 // class ever has member declarations.
2041 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2042 assert(isa<UsingShadowDecl>(FoundDecl));
2043 QualType URecordType = Context.getTypeDeclType(
2044 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2045
2046 // We only need to do this if the naming-class to declaring-class
2047 // conversion is non-trivial.
2048 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2049 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002050 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002051 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002052 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002053 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002054
John McCall6bb80172010-03-30 21:47:33 +00002055 QualType UType = URecordType;
2056 if (PointerConversions)
2057 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002058 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2059 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002060 FromType = UType;
2061 FromRecordType = URecordType;
2062 }
2063
2064 // We don't do access control for the conversion from the
2065 // declaring class to the true declaring class.
2066 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002067 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002068
John McCallf871d0c2010-08-07 06:22:56 +00002069 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002070 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2071 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002072 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002073 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002074
John Wiegley429bb272011-04-08 18:41:53 +00002075 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2076 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002077}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002078
John McCallf7a1a742009-11-24 19:00:30 +00002079bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002080 const LookupResult &R,
2081 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002082 // Only when used directly as the postfix-expression of a call.
2083 if (!HasTrailingLParen)
2084 return false;
2085
2086 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002087 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002088 return false;
2089
2090 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002091 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002092 return false;
2093
2094 // Turn off ADL when we find certain kinds of declarations during
2095 // normal lookup:
2096 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2097 NamedDecl *D = *I;
2098
2099 // C++0x [basic.lookup.argdep]p3:
2100 // -- a declaration of a class member
2101 // Since using decls preserve this property, we check this on the
2102 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002103 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002104 return false;
2105
2106 // C++0x [basic.lookup.argdep]p3:
2107 // -- a block-scope function declaration that is not a
2108 // using-declaration
2109 // NOTE: we also trigger this for function templates (in fact, we
2110 // don't check the decl type at all, since all other decl types
2111 // turn off ADL anyway).
2112 if (isa<UsingShadowDecl>(D))
2113 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2114 else if (D->getDeclContext()->isFunctionOrMethod())
2115 return false;
2116
2117 // C++0x [basic.lookup.argdep]p3:
2118 // -- a declaration that is neither a function or a function
2119 // template
2120 // And also for builtin functions.
2121 if (isa<FunctionDecl>(D)) {
2122 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2123
2124 // But also builtin functions.
2125 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2126 return false;
2127 } else if (!isa<FunctionTemplateDecl>(D))
2128 return false;
2129 }
2130
2131 return true;
2132}
2133
2134
John McCallba135432009-11-21 08:51:07 +00002135/// Diagnoses obvious problems with the use of the given declaration
2136/// as an expression. This is only actually called for lookups that
2137/// were not overloaded, and it doesn't promise that the declaration
2138/// will in fact be used.
2139static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002140 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002141 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2142 return true;
2143 }
2144
2145 if (isa<ObjCInterfaceDecl>(D)) {
2146 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2147 return true;
2148 }
2149
2150 if (isa<NamespaceDecl>(D)) {
2151 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2152 return true;
2153 }
2154
2155 return false;
2156}
2157
John McCall60d7b3a2010-08-24 06:29:42 +00002158ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002159Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002160 LookupResult &R,
2161 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002162 // If this is a single, fully-resolved result and we don't need ADL,
2163 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002164 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002165 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2166 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002167
2168 // We only need to check the declaration if there's exactly one
2169 // result, because in the overloaded case the results can only be
2170 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002171 if (R.isSingleResult() &&
2172 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002173 return ExprError();
2174
John McCallc373d482010-01-27 01:50:18 +00002175 // Otherwise, just build an unresolved lookup expression. Suppress
2176 // any lookup-related diagnostics; we'll hash these out later, when
2177 // we've picked a target.
2178 R.suppressDiagnostics();
2179
John McCallba135432009-11-21 08:51:07 +00002180 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002181 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002182 SS.getWithLocInContext(Context),
2183 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002184 NeedsADL, R.isOverloadedResult(),
2185 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002186
2187 return Owned(ULE);
2188}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002189
John McCallba135432009-11-21 08:51:07 +00002190/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002191ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002192Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002193 const DeclarationNameInfo &NameInfo,
2194 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002195 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002196 assert(!isa<FunctionTemplateDecl>(D) &&
2197 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002198
Abramo Bagnara25777432010-08-11 22:01:17 +00002199 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002200 if (CheckDeclInExpr(*this, Loc, D))
2201 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002202
Douglas Gregor9af2f522009-12-01 16:58:18 +00002203 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2204 // Specifically diagnose references to class templates that are missing
2205 // a template argument list.
2206 Diag(Loc, diag::err_template_decl_ref)
2207 << Template << SS.getRange();
2208 Diag(Template->getLocation(), diag::note_template_decl_here);
2209 return ExprError();
2210 }
2211
2212 // Make sure that we're referring to a value.
2213 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2214 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002215 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002216 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002217 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002218 return ExprError();
2219 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002220
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002221 // Check whether this declaration can be used. Note that we suppress
2222 // this check when we're going to perform argument-dependent lookup
2223 // on this function name, because this might not be the function
2224 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002225 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002226 return ExprError();
2227
Steve Naroffdd972f22008-09-05 22:11:13 +00002228 // Only create DeclRefExpr's for valid Decl's.
2229 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002230 return ExprError();
2231
John McCall5808ce42011-02-03 08:15:49 +00002232 // Handle members of anonymous structs and unions. If we got here,
2233 // and the reference is to a class member indirect field, then this
2234 // must be the subject of a pointer-to-member expression.
2235 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2236 if (!indirectField->isCXXClassMember())
2237 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2238 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002239
Chris Lattner639e2d32008-10-20 05:16:36 +00002240 // If the identifier reference is inside a block, and it refers to a value
2241 // that is outside the block, create a BlockDeclRefExpr instead of a
2242 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2243 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002244 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002245 // We do not do this for things like enum constants, global variables, etc,
2246 // as they do not get snapshotted.
2247 //
John McCall6b5a61b2011-02-07 10:33:21 +00002248 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002249 case CR_Error:
2250 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002251
John McCall469a1eb2011-02-02 13:00:07 +00002252 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002253 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2254 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2255
2256 case CR_CaptureByRef:
2257 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2258 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002259
2260 case CR_NoCapture: {
2261 // If this reference is not in a block or if the referenced
2262 // variable is within the block, create a normal DeclRefExpr.
2263
2264 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002265 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002266
2267 switch (D->getKind()) {
2268 // Ignore all the non-ValueDecl kinds.
2269#define ABSTRACT_DECL(kind)
2270#define VALUE(type, base)
2271#define DECL(type, base) \
2272 case Decl::type:
2273#include "clang/AST/DeclNodes.inc"
2274 llvm_unreachable("invalid value decl kind");
2275 return ExprError();
2276
2277 // These shouldn't make it here.
2278 case Decl::ObjCAtDefsField:
2279 case Decl::ObjCIvar:
2280 llvm_unreachable("forming non-member reference to ivar?");
2281 return ExprError();
2282
2283 // Enum constants are always r-values and never references.
2284 // Unresolved using declarations are dependent.
2285 case Decl::EnumConstant:
2286 case Decl::UnresolvedUsingValue:
2287 valueKind = VK_RValue;
2288 break;
2289
2290 // Fields and indirect fields that got here must be for
2291 // pointer-to-member expressions; we just call them l-values for
2292 // internal consistency, because this subexpression doesn't really
2293 // exist in the high-level semantics.
2294 case Decl::Field:
2295 case Decl::IndirectField:
2296 assert(getLangOptions().CPlusPlus &&
2297 "building reference to field in C?");
2298
2299 // These can't have reference type in well-formed programs, but
2300 // for internal consistency we do this anyway.
2301 type = type.getNonReferenceType();
2302 valueKind = VK_LValue;
2303 break;
2304
2305 // Non-type template parameters are either l-values or r-values
2306 // depending on the type.
2307 case Decl::NonTypeTemplateParm: {
2308 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2309 type = reftype->getPointeeType();
2310 valueKind = VK_LValue; // even if the parameter is an r-value reference
2311 break;
2312 }
2313
2314 // For non-references, we need to strip qualifiers just in case
2315 // the template parameter was declared as 'const int' or whatever.
2316 valueKind = VK_RValue;
2317 type = type.getUnqualifiedType();
2318 break;
2319 }
2320
2321 case Decl::Var:
2322 // In C, "extern void blah;" is valid and is an r-value.
2323 if (!getLangOptions().CPlusPlus &&
2324 !type.hasQualifiers() &&
2325 type->isVoidType()) {
2326 valueKind = VK_RValue;
2327 break;
2328 }
2329 // fallthrough
2330
2331 case Decl::ImplicitParam:
2332 case Decl::ParmVar:
2333 // These are always l-values.
2334 valueKind = VK_LValue;
2335 type = type.getNonReferenceType();
2336 break;
2337
2338 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002339 const FunctionType *fty = type->castAs<FunctionType>();
2340
2341 // If we're referring to a function with an __unknown_anytype
2342 // result type, make the entire expression __unknown_anytype.
2343 if (fty->getResultType() == Context.UnknownAnyTy) {
2344 type = Context.UnknownAnyTy;
2345 valueKind = VK_RValue;
2346 break;
2347 }
2348
John McCall76a40212011-02-09 01:13:10 +00002349 // Functions are l-values in C++.
2350 if (getLangOptions().CPlusPlus) {
2351 valueKind = VK_LValue;
2352 break;
2353 }
2354
2355 // C99 DR 316 says that, if a function type comes from a
2356 // function definition (without a prototype), that type is only
2357 // used for checking compatibility. Therefore, when referencing
2358 // the function, we pretend that we don't have the full function
2359 // type.
John McCall755d8492011-04-12 00:42:48 +00002360 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2361 isa<FunctionProtoType>(fty))
2362 type = Context.getFunctionNoProtoType(fty->getResultType(),
2363 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002364
2365 // Functions are r-values in C.
2366 valueKind = VK_RValue;
2367 break;
2368 }
2369
2370 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002371 // If we're referring to a method with an __unknown_anytype
2372 // result type, make the entire expression __unknown_anytype.
2373 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002374 if (const FunctionProtoType *proto
2375 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002376 if (proto->getResultType() == Context.UnknownAnyTy) {
2377 type = Context.UnknownAnyTy;
2378 valueKind = VK_RValue;
2379 break;
2380 }
2381
John McCall76a40212011-02-09 01:13:10 +00002382 // C++ methods are l-values if static, r-values if non-static.
2383 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2384 valueKind = VK_LValue;
2385 break;
2386 }
2387 // fallthrough
2388
2389 case Decl::CXXConversion:
2390 case Decl::CXXDestructor:
2391 case Decl::CXXConstructor:
2392 valueKind = VK_RValue;
2393 break;
2394 }
2395
2396 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2397 }
2398
John McCall469a1eb2011-02-02 13:00:07 +00002399 }
John McCallf89e55a2010-11-18 06:31:45 +00002400
John McCall6b5a61b2011-02-07 10:33:21 +00002401 llvm_unreachable("unknown capture result");
2402 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002403}
2404
John McCall755d8492011-04-12 00:42:48 +00002405ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002406 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002407
Reid Spencer5f016e22007-07-11 17:01:13 +00002408 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002409 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002410 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2411 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2412 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002413 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002414
Chris Lattnerfa28b302008-01-12 08:14:25 +00002415 // Pre-defined identifiers are of type char[x], where x is the length of the
2416 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002417
Anders Carlsson3a082d82009-09-08 18:24:21 +00002418 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002419 if (!currentDecl && getCurBlock())
2420 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002421 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002422 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002423 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002424 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002425
Anders Carlsson773f3972009-09-11 01:22:35 +00002426 QualType ResTy;
2427 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2428 ResTy = Context.DependentTy;
2429 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002430 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002431
Anders Carlsson773f3972009-09-11 01:22:35 +00002432 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002433 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002434 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2435 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002436 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002437}
2438
John McCall60d7b3a2010-08-24 06:29:42 +00002439ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002440 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002441 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002442 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002443 if (Invalid)
2444 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002445
Benjamin Kramerddeea562010-02-27 13:44:12 +00002446 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002447 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002448 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002449 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002450
Chris Lattnere8337df2009-12-30 21:19:39 +00002451 QualType Ty;
2452 if (!getLangOptions().CPlusPlus)
2453 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2454 else if (Literal.isWide())
2455 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002456 else if (Literal.isUTF16())
2457 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2458 else if (Literal.isUTF32())
2459 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002460 else if (Literal.isMultiChar())
2461 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002462 else
2463 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002464
Douglas Gregor5cee1192011-07-27 05:40:30 +00002465 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2466 if (Literal.isWide())
2467 Kind = CharacterLiteral::Wide;
2468 else if (Literal.isUTF16())
2469 Kind = CharacterLiteral::UTF16;
2470 else if (Literal.isUTF32())
2471 Kind = CharacterLiteral::UTF32;
2472
2473 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2474 Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002475}
2476
John McCall60d7b3a2010-08-24 06:29:42 +00002477ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002478 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002479 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2480 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002481 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002482 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002483 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002484 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002485 }
Ted Kremenek28396602009-01-13 23:19:12 +00002486
Reid Spencer5f016e22007-07-11 17:01:13 +00002487 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002488 // Add padding so that NumericLiteralParser can overread by one character.
2489 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002490 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002491
Reid Spencer5f016e22007-07-11 17:01:13 +00002492 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002493 bool Invalid = false;
2494 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2495 if (Invalid)
2496 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002497
Mike Stump1eb44332009-09-09 15:08:12 +00002498 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002499 Tok.getLocation(), PP);
2500 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002501 return ExprError();
2502
Chris Lattner5d661452007-08-26 03:42:43 +00002503 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002504
Chris Lattner5d661452007-08-26 03:42:43 +00002505 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002506 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002507 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002508 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002509 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002510 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002511 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002512 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002513
2514 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2515
John McCall94c939d2009-12-24 09:08:04 +00002516 using llvm::APFloat;
2517 APFloat Val(Format);
2518
2519 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002520
2521 // Overflow is always an error, but underflow is only an error if
2522 // we underflowed to zero (APFloat reports denormals as underflow).
2523 if ((result & APFloat::opOverflow) ||
2524 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002525 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002526 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002527 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002528 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002529 APFloat::getLargest(Format).toString(buffer);
2530 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002531 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002532 APFloat::getSmallest(Format).toString(buffer);
2533 }
2534
2535 Diag(Tok.getLocation(), diagnostic)
2536 << Ty
Chris Lattner5f9e2722011-07-23 10:55:15 +00002537 << StringRef(buffer.data(), buffer.size());
John McCall94c939d2009-12-24 09:08:04 +00002538 }
2539
2540 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002541 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002542
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002543 if (Ty == Context.DoubleTy) {
2544 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002545 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002546 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2547 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002548 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002549 }
2550 }
Chris Lattner5d661452007-08-26 03:42:43 +00002551 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002552 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002553 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002554 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002555
Neil Boothb9449512007-08-29 22:00:19 +00002556 // long long is a C99 feature.
2557 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002558 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002559 Diag(Tok.getLocation(), diag::ext_longlong);
2560
Reid Spencer5f016e22007-07-11 17:01:13 +00002561 // Get the value in the widest-possible width.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002562 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002563
Reid Spencer5f016e22007-07-11 17:01:13 +00002564 if (Literal.GetIntegerValue(ResultVal)) {
2565 // If this value didn't fit into uintmax_t, warn and force to ull.
2566 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002567 Ty = Context.UnsignedLongLongTy;
2568 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002569 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002570 } else {
2571 // If this value fits into a ULL, try to figure out what else it fits into
2572 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002573
Reid Spencer5f016e22007-07-11 17:01:13 +00002574 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2575 // be an unsigned int.
2576 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2577
2578 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002579 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002580 if (!Literal.isLong && !Literal.isLongLong) {
2581 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002582 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002583
Reid Spencer5f016e22007-07-11 17:01:13 +00002584 // Does it fit in a unsigned int?
2585 if (ResultVal.isIntN(IntSize)) {
2586 // Does it fit in a signed int?
2587 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002588 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002589 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002590 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002591 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002592 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002593 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002594
Reid Spencer5f016e22007-07-11 17:01:13 +00002595 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002596 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002597 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002598
Reid Spencer5f016e22007-07-11 17:01:13 +00002599 // Does it fit in a unsigned long?
2600 if (ResultVal.isIntN(LongSize)) {
2601 // Does it fit in a signed long?
2602 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002603 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002604 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002605 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002606 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002607 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002608 }
2609
Reid Spencer5f016e22007-07-11 17:01:13 +00002610 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002611 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002612 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002613
Reid Spencer5f016e22007-07-11 17:01:13 +00002614 // Does it fit in a unsigned long long?
2615 if (ResultVal.isIntN(LongLongSize)) {
2616 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002617 // To be compatible with MSVC, hex integer literals ending with the
2618 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002619 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2620 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002621 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002622 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002623 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002624 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002625 }
2626 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002627
Reid Spencer5f016e22007-07-11 17:01:13 +00002628 // If we still couldn't decide a type, we probably have something that
2629 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002630 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002631 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002632 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002633 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002634 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002635
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002636 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002637 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002638 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002639 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002640 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002641
Chris Lattner5d661452007-08-26 03:42:43 +00002642 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2643 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002644 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002645 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002646
2647 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002648}
2649
John McCall60d7b3a2010-08-24 06:29:42 +00002650ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCall9ae2f072010-08-23 23:25:46 +00002651 SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002652 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002653 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002654}
2655
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002656static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2657 SourceLocation Loc,
2658 SourceRange ArgRange) {
2659 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2660 // scalar or vector data type argument..."
2661 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2662 // type (C99 6.2.5p18) or void.
2663 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2664 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2665 << T << ArgRange;
2666 return true;
2667 }
2668
2669 assert((T->isVoidType() || !T->isIncompleteType()) &&
2670 "Scalar types should always be complete");
2671 return false;
2672}
2673
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002674static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2675 SourceLocation Loc,
2676 SourceRange ArgRange,
2677 UnaryExprOrTypeTrait TraitKind) {
2678 // C99 6.5.3.4p1:
2679 if (T->isFunctionType()) {
2680 // alignof(function) is allowed as an extension.
2681 if (TraitKind == UETT_SizeOf)
2682 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2683 return false;
2684 }
2685
2686 // Allow sizeof(void)/alignof(void) as an extension.
2687 if (T->isVoidType()) {
2688 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2689 return false;
2690 }
2691
2692 return true;
2693}
2694
2695static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2696 SourceLocation Loc,
2697 SourceRange ArgRange,
2698 UnaryExprOrTypeTrait TraitKind) {
2699 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2700 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2701 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2702 << T << (TraitKind == UETT_SizeOf)
2703 << ArgRange;
2704 return true;
2705 }
2706
2707 return false;
2708}
2709
Chandler Carruth9d342d02011-05-26 08:53:10 +00002710/// \brief Check the constrains on expression operands to unary type expression
2711/// and type traits.
2712///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002713/// Completes any types necessary and validates the constraints on the operand
2714/// expression. The logic mostly mirrors the type-based overload, but may modify
2715/// the expression as it completes the type for that expression through template
2716/// instantiation, etc.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002717bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
2718 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002719 QualType ExprTy = Op->getType();
2720
2721 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2722 // the result is the size of the referenced type."
2723 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2724 // result shall be the alignment of the referenced type."
2725 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2726 ExprTy = Ref->getPointeeType();
2727
2728 if (ExprKind == UETT_VecStep)
2729 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2730 Op->getSourceRange());
2731
2732 // Whitelist some types as extensions
2733 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2734 Op->getSourceRange(), ExprKind))
2735 return false;
2736
2737 if (RequireCompleteExprType(Op,
2738 PDiag(diag::err_sizeof_alignof_incomplete_type)
2739 << ExprKind << Op->getSourceRange(),
2740 std::make_pair(SourceLocation(), PDiag(0))))
2741 return true;
2742
2743 // Completeing the expression's type may have changed it.
2744 ExprTy = Op->getType();
2745 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2746 ExprTy = Ref->getPointeeType();
2747
2748 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
2749 Op->getSourceRange(), ExprKind))
2750 return true;
2751
Nico Webercf739922011-06-15 02:47:03 +00002752 if (ExprKind == UETT_SizeOf) {
2753 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
2754 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2755 QualType OType = PVD->getOriginalType();
2756 QualType Type = PVD->getType();
2757 if (Type->isPointerType() && OType->isArrayType()) {
2758 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
2759 << Type << OType;
2760 Diag(PVD->getLocation(), diag::note_declared_at);
2761 }
2762 }
2763 }
2764 }
2765
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002766 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00002767}
2768
2769/// \brief Check the constraints on operands to unary expression and type
2770/// traits.
2771///
2772/// This will complete any types necessary, and validate the various constraints
2773/// on those operands.
2774///
Reid Spencer5f016e22007-07-11 17:01:13 +00002775/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002776/// C99 6.3.2.1p[2-4] all state:
2777/// Except when it is the operand of the sizeof operator ...
2778///
2779/// C++ [expr.sizeof]p4
2780/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2781/// standard conversions are not applied to the operand of sizeof.
2782///
2783/// This policy is followed for all of the unary trait expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002784bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2785 SourceLocation OpLoc,
2786 SourceRange ExprRange,
2787 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl28507842009-02-26 14:39:58 +00002788 if (exprType->isDependentType())
2789 return false;
2790
Sebastian Redl5d484e82009-11-23 17:18:46 +00002791 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2792 // the result is the size of the referenced type."
2793 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2794 // result shall be the alignment of the referenced type."
2795 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2796 exprType = Ref->getPointeeType();
2797
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002798 if (ExprKind == UETT_VecStep)
2799 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002800
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002801 // Whitelist some types as extensions
2802 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
2803 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00002804 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002805
Chris Lattner1efaa952009-04-24 00:30:45 +00002806 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002807 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002808 << ExprKind << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002809 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002810
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002811 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
2812 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00002813 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002814
Chris Lattner1efaa952009-04-24 00:30:45 +00002815 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002816}
2817
Chandler Carruth9d342d02011-05-26 08:53:10 +00002818static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00002819 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002820
Mike Stump1eb44332009-09-09 15:08:12 +00002821 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002822 if (isa<DeclRefExpr>(E))
2823 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002824
2825 // Cannot know anything else if the expression is dependent.
2826 if (E->isTypeDependent())
2827 return false;
2828
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002829 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002830 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2831 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002832 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002833 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002834
2835 // Alignment of a field access is always okay, so long as it isn't a
2836 // bit-field.
2837 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002838 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002839 return false;
2840
Chandler Carruth9d342d02011-05-26 08:53:10 +00002841 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002842}
2843
Chandler Carruth9d342d02011-05-26 08:53:10 +00002844bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002845 E = E->IgnoreParens();
2846
2847 // Cannot know anything else if the expression is dependent.
2848 if (E->isTypeDependent())
2849 return false;
2850
Chandler Carruth9d342d02011-05-26 08:53:10 +00002851 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00002852}
2853
Douglas Gregorba498172009-03-13 21:01:28 +00002854/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002855ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002856Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2857 SourceLocation OpLoc,
2858 UnaryExprOrTypeTrait ExprKind,
2859 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002860 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002861 return ExprError();
2862
John McCalla93c9342009-12-07 02:54:59 +00002863 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002864
Douglas Gregorba498172009-03-13 21:01:28 +00002865 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002866 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00002867 return ExprError();
2868
2869 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002870 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2871 Context.getSizeType(),
2872 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002873}
2874
2875/// \brief Build a sizeof or alignof expression given an expression
2876/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002877ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002878Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2879 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00002880 ExprResult PE = CheckPlaceholderExpr(E);
2881 if (PE.isInvalid())
2882 return ExprError();
2883
2884 E = PE.get();
2885
Douglas Gregorba498172009-03-13 21:01:28 +00002886 // Verify that the operand is valid.
2887 bool isInvalid = false;
2888 if (E->isTypeDependent()) {
2889 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002890 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002891 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002892 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002893 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002894 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002895 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00002896 isInvalid = true;
2897 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002898 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00002899 }
2900
2901 if (isInvalid)
2902 return ExprError();
2903
2904 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002905 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002906 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002907 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002908}
2909
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002910/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2911/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00002912/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00002913ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002914Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2915 UnaryExprOrTypeTrait ExprKind, bool isType,
2916 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002917 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002918 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002919
Sebastian Redl05189992008-11-11 17:56:53 +00002920 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00002921 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00002922 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002923 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002924 }
Sebastian Redl05189992008-11-11 17:56:53 +00002925
Douglas Gregorba498172009-03-13 21:01:28 +00002926 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002927 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregorba498172009-03-13 21:01:28 +00002928 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002929}
2930
John Wiegley429bb272011-04-08 18:41:53 +00002931static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall09431682010-11-18 19:01:18 +00002932 bool isReal) {
John Wiegley429bb272011-04-08 18:41:53 +00002933 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00002934 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002935
John McCallf6a16482010-12-04 03:47:34 +00002936 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00002937 if (V.get()->getObjectKind() != OK_Ordinary) {
2938 V = S.DefaultLvalueConversion(V.take());
2939 if (V.isInvalid())
2940 return QualType();
2941 }
John McCallf6a16482010-12-04 03:47:34 +00002942
Chris Lattnercc26ed72007-08-26 05:39:26 +00002943 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00002944 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002945 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002946
Chris Lattnercc26ed72007-08-26 05:39:26 +00002947 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00002948 if (V.get()->getType()->isArithmeticType())
2949 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002950
John McCall2cd11fe2010-10-12 02:09:17 +00002951 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00002952 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00002953 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00002954 if (PR.get() != V.get()) {
2955 V = move(PR);
John McCall09431682010-11-18 19:01:18 +00002956 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall2cd11fe2010-10-12 02:09:17 +00002957 }
2958
Chris Lattnercc26ed72007-08-26 05:39:26 +00002959 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00002960 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002961 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00002962 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00002963}
2964
2965
Reid Spencer5f016e22007-07-11 17:01:13 +00002966
John McCall60d7b3a2010-08-24 06:29:42 +00002967ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00002968Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002969 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00002970 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00002971 switch (Kind) {
2972 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00002973 case tok::plusplus: Opc = UO_PostInc; break;
2974 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002975 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002976
John McCall9ae2f072010-08-23 23:25:46 +00002977 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002978}
2979
John McCall60d7b3a2010-08-24 06:29:42 +00002980ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002981Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2982 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00002983 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00002984 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00002985 if (Result.isInvalid()) return ExprError();
2986 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002987
John McCall9ae2f072010-08-23 23:25:46 +00002988 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00002989
Douglas Gregor337c6b92008-11-19 17:17:41 +00002990 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002991 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002992 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00002993 Context.DependentTy,
2994 VK_LValue, OK_Ordinary,
2995 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002996 }
2997
Mike Stump1eb44332009-09-09 15:08:12 +00002998 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00002999 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003000 LHSExp->getType()->isEnumeralType() ||
3001 RHSExp->getType()->isRecordType() ||
3002 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00003003 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003004 }
3005
John McCall9ae2f072010-08-23 23:25:46 +00003006 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003007}
3008
3009
John McCall60d7b3a2010-08-24 06:29:42 +00003010ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003011Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3012 Expr *Idx, SourceLocation RLoc) {
3013 Expr *LHSExp = Base;
3014 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003015
Chris Lattner12d9ff62007-07-16 00:14:47 +00003016 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003017 if (!LHSExp->getType()->getAs<VectorType>()) {
3018 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3019 if (Result.isInvalid())
3020 return ExprError();
3021 LHSExp = Result.take();
3022 }
3023 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3024 if (Result.isInvalid())
3025 return ExprError();
3026 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003027
Chris Lattner12d9ff62007-07-16 00:14:47 +00003028 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003029 ExprValueKind VK = VK_LValue;
3030 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003031
Reid Spencer5f016e22007-07-11 17:01:13 +00003032 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003033 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003034 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003035 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003036 Expr *BaseExpr, *IndexExpr;
3037 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003038 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3039 BaseExpr = LHSExp;
3040 IndexExpr = RHSExp;
3041 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003042 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003043 BaseExpr = LHSExp;
3044 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003045 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003046 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00003047 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00003048 BaseExpr = RHSExp;
3049 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003050 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003051 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003052 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003053 BaseExpr = LHSExp;
3054 IndexExpr = RHSExp;
3055 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003056 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003057 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003058 // Handle the uncommon case of "123[Ptr]".
3059 BaseExpr = RHSExp;
3060 IndexExpr = LHSExp;
3061 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003062 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003063 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003064 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003065 VK = LHSExp->getValueKind();
3066 if (VK != VK_RValue)
3067 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003068
Chris Lattner12d9ff62007-07-16 00:14:47 +00003069 // FIXME: need to deal with const...
3070 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003071 } else if (LHSTy->isArrayType()) {
3072 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003073 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003074 // wasn't promoted because of the C90 rule that doesn't
3075 // allow promoting non-lvalue arrays. Warn, then
3076 // force the promotion here.
3077 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3078 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003079 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3080 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003081 LHSTy = LHSExp->getType();
3082
3083 BaseExpr = LHSExp;
3084 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003085 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003086 } else if (RHSTy->isArrayType()) {
3087 // Same as previous, except for 123[f().a] case
3088 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3089 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003090 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3091 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003092 RHSTy = RHSExp->getType();
3093
3094 BaseExpr = RHSExp;
3095 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003096 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003097 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003098 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3099 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003100 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003101 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003102 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003103 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3104 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003105
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003106 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003107 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3108 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003109 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3110
Douglas Gregore7450f52009-03-24 19:52:54 +00003111 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003112 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3113 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003114 // incomplete types are not object types.
3115 if (ResultType->isFunctionType()) {
3116 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3117 << ResultType << BaseExpr->getSourceRange();
3118 return ExprError();
3119 }
Mike Stump1eb44332009-09-09 15:08:12 +00003120
Abramo Bagnara46358452010-09-13 06:50:07 +00003121 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3122 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003123 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3124 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003125
3126 // C forbids expressions of unqualified void type from being l-values.
3127 // See IsCForbiddenLValueType.
3128 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003129 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003130 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003131 PDiag(diag::err_subscript_incomplete_type)
3132 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003133 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003134
Chris Lattner1efaa952009-04-24 00:30:45 +00003135 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003136 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003137 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3138 << ResultType << BaseExpr->getSourceRange();
3139 return ExprError();
3140 }
Mike Stump1eb44332009-09-09 15:08:12 +00003141
John McCall09431682010-11-18 19:01:18 +00003142 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003143 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003144
Mike Stumpeed9cac2009-02-19 03:04:26 +00003145 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003146 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003147}
3148
John McCall60d7b3a2010-08-24 06:29:42 +00003149ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003150 FunctionDecl *FD,
3151 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003152 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003153 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003154 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003155 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003156 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003157 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003158 return ExprError();
3159 }
3160
3161 if (Param->hasUninstantiatedDefaultArg()) {
3162 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003163
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003164 // Instantiate the expression.
3165 MultiLevelTemplateArgumentList ArgList
3166 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003167
Nico Weber08e41a62010-11-29 18:19:25 +00003168 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003169 = ArgList.getInnermost();
3170 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3171 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003172
Nico Weber08e41a62010-11-29 18:19:25 +00003173 ExprResult Result;
3174 {
3175 // C++ [dcl.fct.default]p5:
3176 // The names in the [default argument] expression are bound, and
3177 // the semantic constraints are checked, at the point where the
3178 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003179 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00003180 Result = SubstExpr(UninstExpr, ArgList);
3181 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003182 if (Result.isInvalid())
3183 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003184
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003185 // Check the expression as an initializer for the parameter.
3186 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003187 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003188 InitializationKind Kind
3189 = InitializationKind::CreateCopy(Param->getLocation(),
3190 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3191 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003192
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003193 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3194 Result = InitSeq.Perform(*this, Entity, Kind,
3195 MultiExprArg(*this, &ResultE, 1));
3196 if (Result.isInvalid())
3197 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003198
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003199 // Build the default argument expression.
3200 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3201 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003202 }
3203
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003204 // If the default expression creates temporaries, we need to
3205 // push them to the current stack of expression temporaries so they'll
3206 // be properly destroyed.
3207 // FIXME: We should really be rebuilding the default argument with new
3208 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003209 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3210 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3211 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3212 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3213 ExprTemporaries.push_back(Temporary);
John McCallf85e1932011-06-15 23:02:42 +00003214 ExprNeedsCleanups = true;
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003215 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003216
3217 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003218 // Just mark all of the declarations in this potentially-evaluated expression
3219 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003220 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00003221 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003222}
3223
Douglas Gregor88a35142008-12-22 05:46:06 +00003224/// ConvertArgumentsForCall - Converts the arguments specified in
3225/// Args/NumArgs to the parameter types of the function FDecl with
3226/// function prototype Proto. Call is the call expression itself, and
3227/// Fn is the function expression. For a C++ member function, this
3228/// routine does not attempt to convert the object argument. Returns
3229/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003230bool
3231Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003232 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003233 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003234 Expr **Args, unsigned NumArgs,
3235 SourceLocation RParenLoc) {
John McCall8e10f3b2011-02-26 05:39:39 +00003236 // Bail out early if calling a builtin with custom typechecking.
3237 // We don't need to do this in the
3238 if (FDecl)
3239 if (unsigned ID = FDecl->getBuiltinID())
3240 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3241 return false;
3242
Mike Stumpeed9cac2009-02-19 03:04:26 +00003243 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003244 // assignment, to the types of the corresponding parameter, ...
3245 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003246 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003247
Douglas Gregor88a35142008-12-22 05:46:06 +00003248 // If too few arguments are available (and we don't have default
3249 // arguments for the remaining parameters), don't make the call.
3250 if (NumArgs < NumArgsInProto) {
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003251 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) {
3252 Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003253 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00003254 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003255
3256 // Emit the location of the prototype.
3257 if (FDecl && !FDecl->getBuiltinID())
3258 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3259 << FDecl;
3260
3261 return true;
3262 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003263 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003264 }
3265
3266 // If too many are passed and not variadic, error on the extras and drop
3267 // them.
3268 if (NumArgs > NumArgsInProto) {
3269 if (!Proto->isVariadic()) {
3270 Diag(Args[NumArgsInProto]->getLocStart(),
3271 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003272 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00003273 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00003274 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3275 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003276
3277 // Emit the location of the prototype.
3278 if (FDecl && !FDecl->getBuiltinID())
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003279 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3280 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003281
Douglas Gregor88a35142008-12-22 05:46:06 +00003282 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003283 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003284 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003285 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003286 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003287 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003288 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003289 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3290 if (Fn->getType()->isBlockPointerType())
3291 CallType = VariadicBlock; // Block
3292 else if (isa<MemberExpr>(Fn))
3293 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003294 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003295 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003296 if (Invalid)
3297 return true;
3298 unsigned TotalNumArgs = AllArgs.size();
3299 for (unsigned i = 0; i < TotalNumArgs; ++i)
3300 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003301
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003302 return false;
3303}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003304
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003305bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3306 FunctionDecl *FDecl,
3307 const FunctionProtoType *Proto,
3308 unsigned FirstProtoArg,
3309 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003310 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003311 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003312 unsigned NumArgsInProto = Proto->getNumArgs();
3313 unsigned NumArgsToCheck = NumArgs;
3314 bool Invalid = false;
3315 if (NumArgs != NumArgsInProto)
3316 // Use default arguments for missing arguments
3317 NumArgsToCheck = NumArgsInProto;
3318 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003319 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003320 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003321 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003322
Douglas Gregor88a35142008-12-22 05:46:06 +00003323 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003324 if (ArgIx < NumArgs) {
3325 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003326
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003327 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3328 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003329 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003330 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003331 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003332
Douglas Gregora188ff22009-12-22 16:09:06 +00003333 // Pass the argument
3334 ParmVarDecl *Param = 0;
3335 if (FDecl && i < FDecl->getNumParams())
3336 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003337
Douglas Gregora188ff22009-12-22 16:09:06 +00003338 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003339 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003340 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3341 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003342 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003343 SourceLocation(),
3344 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00003345 if (ArgE.isInvalid())
3346 return true;
3347
3348 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003349 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003350 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003351
John McCall60d7b3a2010-08-24 06:29:42 +00003352 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003353 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003354 if (ArgExpr.isInvalid())
3355 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003356
Anders Carlsson56c5e332009-08-25 03:49:14 +00003357 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003358 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003359
3360 // Check for array bounds violations for each argument to the call. This
3361 // check only triggers warnings when the argument isn't a more complex Expr
3362 // with its own checking, such as a BinaryOperator.
3363 CheckArrayAccess(Arg);
3364
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003365 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003366 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003367
Douglas Gregor88a35142008-12-22 05:46:06 +00003368 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003369 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003370
3371 // Assume that extern "C" functions with variadic arguments that
3372 // return __unknown_anytype aren't *really* variadic.
3373 if (Proto->getResultType() == Context.UnknownAnyTy &&
3374 FDecl && FDecl->isExternC()) {
3375 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3376 ExprResult arg;
3377 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3378 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3379 else
3380 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3381 Invalid |= arg.isInvalid();
3382 AllArgs.push_back(arg.take());
3383 }
3384
3385 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3386 } else {
3387 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003388 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3389 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003390 Invalid |= Arg.isInvalid();
3391 AllArgs.push_back(Arg.take());
3392 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003393 }
3394 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003395 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003396}
3397
John McCall755d8492011-04-12 00:42:48 +00003398/// Given a function expression of unknown-any type, try to rebuild it
3399/// to have a function type.
3400static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3401
Steve Narofff69936d2007-09-16 03:34:24 +00003402/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003403/// This provides the location of the left/right parens and a list of comma
3404/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003405ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003406Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003407 MultiExprArg args, SourceLocation RParenLoc,
3408 Expr *ExecConfig) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003409 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003410
3411 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003412 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003413 if (Result.isInvalid()) return ExprError();
3414 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003415
John McCall9ae2f072010-08-23 23:25:46 +00003416 Expr **Args = args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003417
Douglas Gregor88a35142008-12-22 05:46:06 +00003418 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003419 // If this is a pseudo-destructor expression, build the call immediately.
3420 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3421 if (NumArgs > 0) {
3422 // Pseudo-destructor calls should not have any arguments.
3423 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003424 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003425 SourceRange(Args[0]->getLocStart(),
3426 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003427
Douglas Gregora71d8192009-09-04 17:36:40 +00003428 NumArgs = 0;
3429 }
Mike Stump1eb44332009-09-09 15:08:12 +00003430
Douglas Gregora71d8192009-09-04 17:36:40 +00003431 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00003432 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003433 }
Mike Stump1eb44332009-09-09 15:08:12 +00003434
Douglas Gregor17330012009-02-04 15:01:18 +00003435 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003436 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003437 // FIXME: Will need to cache the results of name lookup (including ADL) in
3438 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003439 bool Dependent = false;
3440 if (Fn->isTypeDependent())
3441 Dependent = true;
3442 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3443 Dependent = true;
3444
Peter Collingbournee08ce652011-02-09 21:07:24 +00003445 if (Dependent) {
3446 if (ExecConfig) {
3447 return Owned(new (Context) CUDAKernelCallExpr(
3448 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3449 Context.DependentTy, VK_RValue, RParenLoc));
3450 } else {
3451 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3452 Context.DependentTy, VK_RValue,
3453 RParenLoc));
3454 }
3455 }
Douglas Gregor17330012009-02-04 15:01:18 +00003456
3457 // Determine whether this is a call to an object (C++ [over.call.object]).
3458 if (Fn->getType()->isRecordType())
3459 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003460 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003461
John McCall755d8492011-04-12 00:42:48 +00003462 if (Fn->getType() == Context.UnknownAnyTy) {
3463 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3464 if (result.isInvalid()) return ExprError();
3465 Fn = result.take();
3466 }
3467
John McCall864c0412011-04-26 20:42:42 +00003468 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00003469 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003470 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003471 }
John McCall864c0412011-04-26 20:42:42 +00003472 }
John McCall129e2df2009-11-30 22:42:35 +00003473
John McCall864c0412011-04-26 20:42:42 +00003474 // Check for overloaded calls. This can happen even in C due to extensions.
3475 if (Fn->getType() == Context.OverloadTy) {
3476 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3477
3478 // We aren't supposed to apply this logic if there's an '&' involved.
3479 if (!find.IsAddressOfOperand) {
3480 OverloadExpr *ovl = find.Expression;
3481 if (isa<UnresolvedLookupExpr>(ovl)) {
3482 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3483 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3484 RParenLoc, ExecConfig);
3485 } else {
John McCallaa81e162009-12-01 22:10:20 +00003486 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003487 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003488 }
3489 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003490 }
3491
Douglas Gregorfa047642009-02-04 00:32:51 +00003492 // If we're directly calling a function, get the appropriate declaration.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003493
Eli Friedmanefa42f72009-12-26 03:35:45 +00003494 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003495
John McCall3b4294e2009-12-16 12:17:52 +00003496 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003497 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3498 if (UnOp->getOpcode() == UO_AddrOf)
3499 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3500
John McCall3b4294e2009-12-16 12:17:52 +00003501 if (isa<DeclRefExpr>(NakedFn))
3502 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003503 else if (isa<MemberExpr>(NakedFn))
3504 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003505
Peter Collingbournee08ce652011-02-09 21:07:24 +00003506 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3507 ExecConfig);
3508}
3509
3510ExprResult
3511Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3512 MultiExprArg execConfig, SourceLocation GGGLoc) {
3513 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3514 if (!ConfigDecl)
3515 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3516 << "cudaConfigureCall");
3517 QualType ConfigQTy = ConfigDecl->getType();
3518
3519 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3520 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3521
3522 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCallaa81e162009-12-01 22:10:20 +00003523}
3524
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003525/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3526///
3527/// __builtin_astype( value, dst type )
3528///
3529ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
3530 SourceLocation BuiltinLoc,
3531 SourceLocation RParenLoc) {
3532 ExprValueKind VK = VK_RValue;
3533 ExprObjectKind OK = OK_Ordinary;
3534 QualType DstTy = GetTypeFromParser(destty);
3535 QualType SrcTy = expr->getType();
3536 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3537 return ExprError(Diag(BuiltinLoc,
3538 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003539 << DstTy
3540 << SrcTy
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003541 << expr->getSourceRange());
Richard Trieu67e29332011-08-02 04:35:43 +00003542 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc,
3543 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003544}
3545
John McCall3b4294e2009-12-16 12:17:52 +00003546/// BuildResolvedCallExpr - Build a call to a resolved expression,
3547/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003548/// unary-convert to an expression of function-pointer or
3549/// block-pointer type.
3550///
3551/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003552ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003553Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3554 SourceLocation LParenLoc,
3555 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003556 SourceLocation RParenLoc,
3557 Expr *Config) {
John McCallaa81e162009-12-01 22:10:20 +00003558 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3559
Chris Lattner04421082008-04-08 04:40:51 +00003560 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00003561 ExprResult Result = UsualUnaryConversions(Fn);
3562 if (Result.isInvalid())
3563 return ExprError();
3564 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00003565
Chris Lattner925e60d2007-12-28 05:29:59 +00003566 // Make the call expr early, before semantic checks. This guarantees cleanup
3567 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00003568 CallExpr *TheCall;
3569 if (Config) {
3570 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3571 cast<CallExpr>(Config),
3572 Args, NumArgs,
3573 Context.BoolTy,
3574 VK_RValue,
3575 RParenLoc);
3576 } else {
3577 TheCall = new (Context) CallExpr(Context, Fn,
3578 Args, NumArgs,
3579 Context.BoolTy,
3580 VK_RValue,
3581 RParenLoc);
3582 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003583
John McCall8e10f3b2011-02-26 05:39:39 +00003584 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3585
3586 // Bail out early if calling a builtin with custom typechecking.
3587 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3588 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3589
John McCall1de4d4e2011-04-07 08:22:57 +00003590 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00003591 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00003592 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00003593 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3594 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00003595 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00003596 if (FuncT == 0)
3597 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3598 << Fn->getType() << Fn->getSourceRange());
3599 } else if (const BlockPointerType *BPT =
3600 Fn->getType()->getAs<BlockPointerType>()) {
3601 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3602 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00003603 // Handle calls to expressions of unknown-any type.
3604 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00003605 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003606 if (rewrite.isInvalid()) return ExprError();
3607 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00003608 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003609 goto retry;
3610 }
3611
Sebastian Redl0eb23302009-01-19 00:08:26 +00003612 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3613 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00003614 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003615
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003616 if (getLangOptions().CUDA) {
3617 if (Config) {
3618 // CUDA: Kernel calls must be to global functions
3619 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3620 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3621 << FDecl->getName() << Fn->getSourceRange());
3622
3623 // CUDA: Kernel function must have 'void' return type
3624 if (!FuncT->getResultType()->isVoidType())
3625 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3626 << Fn->getType() << Fn->getSourceRange());
3627 }
3628 }
3629
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003630 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003631 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00003632 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003633 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003634 return ExprError();
3635
Chris Lattner925e60d2007-12-28 05:29:59 +00003636 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003637 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00003638 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003639
Douglas Gregor72564e72009-02-26 23:50:07 +00003640 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00003641 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003642 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003643 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003644 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003645 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003646
Douglas Gregor74734d52009-04-02 15:37:10 +00003647 if (FDecl) {
3648 // Check if we have too few/too many template arguments, based
3649 // on our knowledge of the function definition.
3650 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00003651 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003652 const FunctionProtoType *Proto
3653 = Def->getType()->getAs<FunctionProtoType>();
3654 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003655 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3656 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003657 }
Douglas Gregor46542412010-10-25 20:39:23 +00003658
3659 // If the function we're calling isn't a function prototype, but we have
3660 // a function prototype from a prior declaratiom, use that prototype.
3661 if (!FDecl->hasPrototype())
3662 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00003663 }
3664
Steve Naroffb291ab62007-08-28 23:30:39 +00003665 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003666 for (unsigned i = 0; i != NumArgs; i++) {
3667 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00003668
3669 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003670 InitializedEntity Entity
3671 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00003672 Proto->getArgType(i),
3673 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00003674 ExprResult ArgE = PerformCopyInitialization(Entity,
3675 SourceLocation(),
3676 Owned(Arg));
3677 if (ArgE.isInvalid())
3678 return true;
3679
3680 Arg = ArgE.takeAs<Expr>();
3681
3682 } else {
John Wiegley429bb272011-04-08 18:41:53 +00003683 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3684
3685 if (ArgE.isInvalid())
3686 return true;
3687
3688 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00003689 }
3690
Douglas Gregor0700bbf2010-10-26 05:45:40 +00003691 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3692 Arg->getType(),
3693 PDiag(diag::err_call_incomplete_argument)
3694 << Arg->getSourceRange()))
3695 return ExprError();
3696
Chris Lattner925e60d2007-12-28 05:29:59 +00003697 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003698 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003699 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003700
Douglas Gregor88a35142008-12-22 05:46:06 +00003701 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3702 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003703 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3704 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003705
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003706 // Check for sentinels
3707 if (NDecl)
3708 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003709
Chris Lattner59907c42007-08-10 20:18:51 +00003710 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003711 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003712 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003713 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003714
John McCall8e10f3b2011-02-26 05:39:39 +00003715 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00003716 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00003717 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003718 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003719 return ExprError();
3720 }
Chris Lattner59907c42007-08-10 20:18:51 +00003721
John McCall9ae2f072010-08-23 23:25:46 +00003722 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00003723}
3724
John McCall60d7b3a2010-08-24 06:29:42 +00003725ExprResult
John McCallb3d87482010-08-24 05:47:05 +00003726Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00003727 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003728 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00003729 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003730 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00003731
3732 TypeSourceInfo *TInfo;
3733 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3734 if (!TInfo)
3735 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3736
John McCall9ae2f072010-08-23 23:25:46 +00003737 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00003738}
3739
John McCall60d7b3a2010-08-24 06:29:42 +00003740ExprResult
John McCall42f56b52010-01-18 19:35:47 +00003741Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00003742 SourceLocation RParenLoc, Expr *literalExpr) {
John McCall42f56b52010-01-18 19:35:47 +00003743 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00003744
Eli Friedman6223c222008-05-20 05:22:08 +00003745 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00003746 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3747 PDiag(diag::err_illegal_decl_array_incomplete_type)
3748 << SourceRange(LParenLoc,
3749 literalExpr->getSourceRange().getEnd())))
3750 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003751 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003752 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3753 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003754 } else if (!literalType->isDependentType() &&
3755 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003756 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003757 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003758 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003759 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003760
Douglas Gregor99a2e602009-12-16 01:38:02 +00003761 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003762 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003763 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00003764 = InitializationKind::CreateCStyleCast(LParenLoc,
3765 SourceRange(LParenLoc, RParenLoc));
Eli Friedman08544622009-12-22 02:35:53 +00003766 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00003767 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00003768 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00003769 &literalType);
3770 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003771 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00003772 literalExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00003773
Chris Lattner371f2582008-12-04 23:50:19 +00003774 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003775 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003776 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003777 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003778 }
Eli Friedman08544622009-12-22 02:35:53 +00003779
John McCallf89e55a2010-11-18 06:31:45 +00003780 // In C, compound literals are l-values for some reason.
3781 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3782
Douglas Gregor751ec9b2011-06-17 04:59:12 +00003783 return MaybeBindToTemporary(
3784 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3785 VK, literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003786}
3787
John McCall60d7b3a2010-08-24 06:29:42 +00003788ExprResult
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003789Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003790 SourceLocation RBraceLoc) {
3791 unsigned NumInit = initlist.size();
John McCall9ae2f072010-08-23 23:25:46 +00003792 Expr **InitList = initlist.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003793
Steve Naroff08d92e42007-09-15 18:49:24 +00003794 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003795 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003796
Ted Kremenek709210f2010-04-13 23:39:13 +00003797 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3798 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003799 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003800 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003801}
3802
John McCallf3ea8cf2010-11-14 08:17:51 +00003803/// Prepares for a scalar cast, performing all the necessary stages
3804/// except the final cast and returning the kind required.
John Wiegley429bb272011-04-08 18:41:53 +00003805static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00003806 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3807 // Also, callers should have filtered out the invalid cases with
3808 // pointers. Everything else should be possible.
3809
John Wiegley429bb272011-04-08 18:41:53 +00003810 QualType SrcTy = Src.get()->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00003811 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00003812 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00003813
John McCalldaa8e4e2010-11-15 09:13:47 +00003814 switch (SrcTy->getScalarTypeKind()) {
3815 case Type::STK_MemberPointer:
3816 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003817
John McCalldaa8e4e2010-11-15 09:13:47 +00003818 case Type::STK_Pointer:
3819 switch (DestTy->getScalarTypeKind()) {
3820 case Type::STK_Pointer:
3821 return DestTy->isObjCObjectPointerType() ?
John McCallf3ea8cf2010-11-14 08:17:51 +00003822 CK_AnyPointerToObjCPointerCast :
3823 CK_BitCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003824 case Type::STK_Bool:
3825 return CK_PointerToBoolean;
3826 case Type::STK_Integral:
3827 return CK_PointerToIntegral;
3828 case Type::STK_Floating:
3829 case Type::STK_FloatingComplex:
3830 case Type::STK_IntegralComplex:
3831 case Type::STK_MemberPointer:
3832 llvm_unreachable("illegal cast from pointer");
3833 }
3834 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003835
John McCalldaa8e4e2010-11-15 09:13:47 +00003836 case Type::STK_Bool: // casting from bool is like casting from an integer
3837 case Type::STK_Integral:
3838 switch (DestTy->getScalarTypeKind()) {
3839 case Type::STK_Pointer:
Richard Trieu67e29332011-08-02 04:35:43 +00003840 if (Src.get()->isNullPointerConstant(S.Context,
3841 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00003842 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00003843 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00003844 case Type::STK_Bool:
3845 return CK_IntegralToBoolean;
3846 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00003847 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003848 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00003849 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00003850 case Type::STK_IntegralComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003851 Src = S.ImpCastExprToType(Src.take(),
3852 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003853 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00003854 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003855 case Type::STK_FloatingComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003856 Src = S.ImpCastExprToType(Src.take(),
3857 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003858 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00003859 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003860 case Type::STK_MemberPointer:
3861 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003862 }
3863 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003864
John McCalldaa8e4e2010-11-15 09:13:47 +00003865 case Type::STK_Floating:
3866 switch (DestTy->getScalarTypeKind()) {
3867 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00003868 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003869 case Type::STK_Bool:
3870 return CK_FloatingToBoolean;
3871 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00003872 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00003873 case Type::STK_FloatingComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003874 Src = S.ImpCastExprToType(Src.take(),
3875 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003876 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00003877 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003878 case Type::STK_IntegralComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003879 Src = S.ImpCastExprToType(Src.take(),
3880 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003881 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00003882 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003883 case Type::STK_Pointer:
3884 llvm_unreachable("valid float->pointer cast?");
3885 case Type::STK_MemberPointer:
3886 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003887 }
3888 break;
3889
John McCalldaa8e4e2010-11-15 09:13:47 +00003890 case Type::STK_FloatingComplex:
3891 switch (DestTy->getScalarTypeKind()) {
3892 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003893 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003894 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003895 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00003896 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003897 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00003898 if (S.Context.hasSameType(ET, DestTy))
3899 return CK_FloatingComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00003900 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00003901 return CK_FloatingCast;
3902 }
John McCalldaa8e4e2010-11-15 09:13:47 +00003903 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00003904 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00003905 case Type::STK_Integral:
Richard Trieu67e29332011-08-02 04:35:43 +00003906 Src = S.ImpCastExprToType(Src.take(),
3907 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003908 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00003909 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00003910 case Type::STK_Pointer:
3911 llvm_unreachable("valid complex float->pointer cast?");
3912 case Type::STK_MemberPointer:
3913 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003914 }
3915 break;
3916
John McCalldaa8e4e2010-11-15 09:13:47 +00003917 case Type::STK_IntegralComplex:
3918 switch (DestTy->getScalarTypeKind()) {
3919 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003920 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003921 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003922 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00003923 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003924 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00003925 if (S.Context.hasSameType(ET, DestTy))
3926 return CK_IntegralComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00003927 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00003928 return CK_IntegralCast;
3929 }
John McCalldaa8e4e2010-11-15 09:13:47 +00003930 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00003931 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00003932 case Type::STK_Floating:
Richard Trieu67e29332011-08-02 04:35:43 +00003933 Src = S.ImpCastExprToType(Src.take(),
3934 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003935 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00003936 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00003937 case Type::STK_Pointer:
3938 llvm_unreachable("valid complex int->pointer cast?");
3939 case Type::STK_MemberPointer:
3940 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003941 }
3942 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00003943 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003944
John McCallf3ea8cf2010-11-14 08:17:51 +00003945 llvm_unreachable("Unhandled scalar cast");
3946 return CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00003947}
3948
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003949/// CheckCastTypes - Check type constraints for casting between types.
John McCallf85e1932011-06-15 23:02:42 +00003950ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
3951 QualType castType, Expr *castExpr,
3952 CastKind& Kind, ExprValueKind &VK,
John Wiegley429bb272011-04-08 18:41:53 +00003953 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall1de4d4e2011-04-07 08:22:57 +00003954 if (castExpr->getType() == Context.UnknownAnyTy)
3955 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
3956
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003957 if (getLangOptions().CPlusPlus)
John McCallf85e1932011-06-15 23:02:42 +00003958 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor40749ee2010-11-03 00:35:38 +00003959 castExpr->getLocEnd()),
John McCallf89e55a2010-11-18 06:31:45 +00003960 castType, VK, castExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003961 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003962
John McCallfb8721c2011-04-10 19:13:55 +00003963 assert(!castExpr->getType()->isPlaceholderType());
3964
John McCallf89e55a2010-11-18 06:31:45 +00003965 // We only support r-value casts in C.
3966 VK = VK_RValue;
3967
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003968 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3969 // type needs to be scalar.
3970 if (castType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00003971 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley429bb272011-04-08 18:41:53 +00003972 ExprResult castExprRes = IgnoredValueConversions(castExpr);
3973 if (castExprRes.isInvalid())
3974 return ExprError();
3975 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00003976
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003977 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00003978 Kind = CK_ToVoid;
John Wiegley429bb272011-04-08 18:41:53 +00003979 return Owned(castExpr);
Anders Carlssonebeaf202009-10-16 02:35:04 +00003980 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003981
John Wiegley429bb272011-04-08 18:41:53 +00003982 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
3983 if (castExprRes.isInvalid())
3984 return ExprError();
3985 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00003986
Eli Friedman8d438082010-07-17 20:43:49 +00003987 if (RequireCompleteType(TyR.getBegin(), castType,
3988 diag::err_typecheck_cast_to_incomplete))
John Wiegley429bb272011-04-08 18:41:53 +00003989 return ExprError();
Eli Friedman8d438082010-07-17 20:43:49 +00003990
Anders Carlssonebeaf202009-10-16 02:35:04 +00003991 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003992 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003993 (castType->isStructureType() || castType->isUnionType())) {
3994 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003995 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003996 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3997 << castType << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003998 Kind = CK_NoOp;
John Wiegley429bb272011-04-08 18:41:53 +00003999 return Owned(castExpr);
Anders Carlssonc3516322009-10-16 02:48:28 +00004000 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004001
Anders Carlssonc3516322009-10-16 02:48:28 +00004002 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004003 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00004004 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004005 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004006 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004007 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004008 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00004009 castExpr->getType()) &&
4010 !Field->isUnnamedBitfield()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004011 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4012 << castExpr->getSourceRange();
4013 break;
4014 }
4015 }
John Wiegley429bb272011-04-08 18:41:53 +00004016 if (Field == FieldEnd) {
4017 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004018 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004019 return ExprError();
4020 }
John McCall2de56d12010-08-25 11:45:40 +00004021 Kind = CK_ToUnion;
John Wiegley429bb272011-04-08 18:41:53 +00004022 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004023 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004024
Anders Carlssonc3516322009-10-16 02:48:28 +00004025 // Reject any other conversions to non-scalar types.
John Wiegley429bb272011-04-08 18:41:53 +00004026 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlssonc3516322009-10-16 02:48:28 +00004027 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004028 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00004029 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004030
John McCallf3ea8cf2010-11-14 08:17:51 +00004031 // The type we're casting to is known to be a scalar or vector.
4032
4033 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004034 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00004035 !castExpr->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004036 Diag(castExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004037 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00004038 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004039 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00004040 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004041
4042 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00004043 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004044
Anton Yartsevd06fea82011-03-27 09:32:40 +00004045 if (castType->isVectorType()) {
4046 if (castType->getAs<VectorType>()->getVectorKind() ==
4047 VectorType::AltiVecVector &&
4048 (castExpr->getType()->isIntegerType() ||
4049 castExpr->getType()->isFloatingType())) {
4050 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004051 return Owned(castExpr);
4052 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
4053 return ExprError();
Anton Yartsevd06fea82011-03-27 09:32:40 +00004054 } else
John Wiegley429bb272011-04-08 18:41:53 +00004055 return Owned(castExpr);
Anton Yartsevd06fea82011-03-27 09:32:40 +00004056 }
John Wiegley429bb272011-04-08 18:41:53 +00004057 if (castExpr->getType()->isVectorType()) {
4058 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
4059 return ExprError();
4060 else
4061 return Owned(castExpr);
4062 }
Anders Carlssonc3516322009-10-16 02:48:28 +00004063
John McCallf3ea8cf2010-11-14 08:17:51 +00004064 // The source and target types are both scalars, i.e.
4065 // - arithmetic types (fundamental, enum, and complex)
4066 // - all kinds of pointers
4067 // Note that member pointers were filtered out with C++, above.
4068
John Wiegley429bb272011-04-08 18:41:53 +00004069 if (isa<ObjCSelectorExpr>(castExpr)) {
4070 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4071 return ExprError();
4072 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004073
John McCallf3ea8cf2010-11-14 08:17:51 +00004074 // If either type is a pointer, the other type has to be either an
4075 // integer or a pointer.
John McCallf85e1932011-06-15 23:02:42 +00004076 QualType castExprType = castExpr->getType();
Anders Carlssonc3516322009-10-16 02:48:28 +00004077 if (!castType->isArithmeticType()) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00004078 if (!castExprType->isIntegralType(Context) &&
John Wiegley429bb272011-04-08 18:41:53 +00004079 castExprType->isArithmeticType()) {
4080 Diag(castExpr->getLocStart(),
4081 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00004082 << castExprType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004083 return ExprError();
4084 }
Eli Friedman41826bb2009-05-01 02:23:58 +00004085 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004086 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
4087 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00004088 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004089 return ExprError();
4090 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004091 }
Anders Carlsson82debc72009-10-18 18:12:03 +00004092
John McCallf85e1932011-06-15 23:02:42 +00004093 if (getLangOptions().ObjCAutoRefCount) {
4094 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
4095 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
4096 castType, castExpr, CCK_CStyleCast);
4097
4098 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
4099 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
4100 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4101 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4102 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4103 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4104 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
4105 Diag(castExpr->getLocStart(),
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00004106 diag::err_typecheck_incompatible_ownership)
John McCallf85e1932011-06-15 23:02:42 +00004107 << castExprType << castType << AA_Casting
4108 << castExpr->getSourceRange();
4109
4110 return ExprError();
4111 }
4112 }
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00004113 }
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00004114 else if (!CheckObjCARCUnavailableWeakConversion(castType, castExprType)) {
4115 Diag(castExpr->getLocStart(),
Fariborz Jahanian82007c32011-07-08 17:41:42 +00004116 diag::err_arc_convesion_of_weak_unavailable) << 1
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00004117 << castExprType << castType
4118 << castExpr->getSourceRange();
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00004119 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00004120 }
4121 }
4122
John Wiegley429bb272011-04-08 18:41:53 +00004123 castExprRes = Owned(castExpr);
4124 Kind = PrepareScalarCast(*this, castExprRes, castType);
4125 if (castExprRes.isInvalid())
4126 return ExprError();
4127 castExpr = castExprRes.take();
John McCallb7f4ffe2010-08-12 21:44:57 +00004128
John McCallf3ea8cf2010-11-14 08:17:51 +00004129 if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00004130 CheckCastAlign(castExpr, castType, TyR);
4131
John Wiegley429bb272011-04-08 18:41:53 +00004132 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004133}
4134
Anders Carlssonc3516322009-10-16 02:48:28 +00004135bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004136 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004137 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004138
Anders Carlssona64db8f2007-11-27 05:51:55 +00004139 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004140 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004141 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004142 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004143 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004144 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004145 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004146 } else
4147 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004148 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004149 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004150
John McCall2de56d12010-08-25 11:45:40 +00004151 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004152 return false;
4153}
4154
John Wiegley429bb272011-04-08 18:41:53 +00004155ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4156 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004157 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004158
Anders Carlsson16a89042009-10-16 05:23:41 +00004159 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004160
Nate Begeman9b10da62009-06-27 22:05:55 +00004161 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4162 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00004163 if (SrcTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004164 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
4165 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004166 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004167 return ExprError();
4168 }
John McCall2de56d12010-08-25 11:45:40 +00004169 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004170 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004171 }
4172
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004173 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004174 // conversion will take place first from scalar to elt type, and then
4175 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004176 if (SrcTy->isPointerType())
4177 return Diag(R.getBegin(),
4178 diag::err_invalid_conversion_between_vector_and_scalar)
4179 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004180
4181 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004182 ExprResult CastExprRes = Owned(CastExpr);
4183 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4184 if (CastExprRes.isInvalid())
4185 return ExprError();
4186 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004187
John McCall2de56d12010-08-25 11:45:40 +00004188 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004189 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004190}
4191
John McCall60d7b3a2010-08-24 06:29:42 +00004192ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004193Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4194 Declarator &D, ParsedType &Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004195 SourceLocation RParenLoc, Expr *castExpr) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004196 assert(!D.isInvalidType() && (castExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004197 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004198
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004199 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, castExpr->getType());
4200 if (D.isInvalidType())
4201 return ExprError();
4202
4203 if (getLangOptions().CPlusPlus) {
4204 // Check that there are no default arguments (C++ only).
4205 CheckExtraCXXDefaultArguments(D);
4206 }
4207
4208 QualType castType = castTInfo->getType();
4209 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004210
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004211 bool isVectorLiteral = false;
4212
4213 // Check for an altivec or OpenCL literal,
4214 // i.e. all the elements are integer constants.
4215 ParenExpr *PE = dyn_cast<ParenExpr>(castExpr);
4216 ParenListExpr *PLE = dyn_cast<ParenListExpr>(castExpr);
4217 if (getLangOptions().AltiVec && castType->isVectorType() && (PE || PLE)) {
4218 if (PLE && PLE->getNumExprs() == 0) {
4219 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4220 return ExprError();
4221 }
4222 if (PE || PLE->getNumExprs() == 1) {
4223 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4224 if (!E->getType()->isVectorType())
4225 isVectorLiteral = true;
4226 }
4227 else
4228 isVectorLiteral = true;
4229 }
4230
4231 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4232 // then handle it as such.
4233 if (isVectorLiteral)
4234 return BuildVectorLiteral(LParenLoc, RParenLoc, castExpr, castTInfo);
4235
Nate Begeman2ef13e52009-08-10 23:49:36 +00004236 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004237 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4238 // sequence of BinOp comma operators.
4239 if (isa<ParenListExpr>(castExpr)) {
4240 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, castExpr);
4241 if (Result.isInvalid()) return ExprError();
4242 castExpr = Result.take();
4243 }
John McCallb042fdf2010-01-15 18:56:44 +00004244
John McCall9ae2f072010-08-23 23:25:46 +00004245 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004246}
4247
John McCall60d7b3a2010-08-24 06:29:42 +00004248ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00004249Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004250 SourceLocation RParenLoc, Expr *castExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004251 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00004252 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00004253 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +00004254 ExprResult CastResult =
John McCallf85e1932011-06-15 23:02:42 +00004255 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
4256 castExpr, Kind, VK, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +00004257 if (CastResult.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004258 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004259 castExpr = CastResult.take();
Anders Carlsson0aebc812009-09-09 21:33:21 +00004260
Richard Trieu67e29332011-08-02 04:35:43 +00004261 return Owned(CStyleCastExpr::Create(
4262 Context, Ty->getType().getNonLValueExprType(Context), VK, Kind, castExpr,
4263 &BasePath, Ty, LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00004264}
4265
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004266ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4267 SourceLocation RParenLoc, Expr *E,
4268 TypeSourceInfo *TInfo) {
4269 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4270 "Expected paren or paren list expression");
4271
4272 Expr **exprs;
4273 unsigned numExprs;
4274 Expr *subExpr;
4275 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4276 exprs = PE->getExprs();
4277 numExprs = PE->getNumExprs();
4278 } else {
4279 subExpr = cast<ParenExpr>(E)->getSubExpr();
4280 exprs = &subExpr;
4281 numExprs = 1;
4282 }
4283
4284 QualType Ty = TInfo->getType();
4285 assert(Ty->isVectorType() && "Expected vector type");
4286
Chris Lattner5f9e2722011-07-23 10:55:15 +00004287 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004288 const VectorType *VTy = Ty->getAs<VectorType>();
4289 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4290
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004291 // '(...)' form of vector initialization in AltiVec: the number of
4292 // initializers must be one or must match the size of the vector.
4293 // If a single value is specified in the initializer then it will be
4294 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004295 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004296 // The number of initializers must be one or must match the size of the
4297 // vector. If a single value is specified in the initializer then it will
4298 // be replicated to all the components of the vector
4299 if (numExprs == 1) {
4300 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4301 ExprResult Literal = Owned(exprs[0]);
4302 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4303 PrepareScalarCast(*this, Literal, ElemTy));
4304 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4305 }
4306 else if (numExprs < numElems) {
4307 Diag(E->getExprLoc(),
4308 diag::err_incorrect_number_of_vector_initializers);
4309 return ExprError();
4310 }
4311 else
4312 for (unsigned i = 0, e = numExprs; i != e; ++i)
4313 initExprs.push_back(exprs[i]);
4314 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004315 else {
4316 // For OpenCL, when the number of initializers is a single value,
4317 // it will be replicated to all components of the vector.
4318 if (getLangOptions().OpenCL &&
4319 VTy->getVectorKind() == VectorType::GenericVector &&
4320 numExprs == 1) {
4321 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4322 ExprResult Literal = Owned(exprs[0]);
4323 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4324 PrepareScalarCast(*this, Literal, ElemTy));
4325 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4326 }
4327
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004328 for (unsigned i = 0, e = numExprs; i != e; ++i)
4329 initExprs.push_back(exprs[i]);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004330 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004331 // FIXME: This means that pretty-printing the final AST will produce curly
4332 // braces instead of the original commas.
4333 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4334 &initExprs[0],
4335 initExprs.size(), RParenLoc);
4336 initE->setType(Ty);
4337 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4338}
4339
Nate Begeman2ef13e52009-08-10 23:49:36 +00004340/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4341/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004342ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004343Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004344 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4345 if (!E)
4346 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00004347
John McCall60d7b3a2010-08-24 06:29:42 +00004348 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004349
Nate Begeman2ef13e52009-08-10 23:49:36 +00004350 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004351 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4352 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004353
John McCall9ae2f072010-08-23 23:25:46 +00004354 if (Result.isInvalid()) return ExprError();
4355
4356 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004357}
4358
John McCall60d7b3a2010-08-24 06:29:42 +00004359ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00004360 SourceLocation R,
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004361 MultiExprArg Val) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004362 unsigned nexprs = Val.size();
4363 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004364 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4365 Expr *expr;
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004366 if (nexprs == 1)
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004367 expr = new (Context) ParenExpr(L, R, exprs[0]);
4368 else
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004369 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4370 exprs[nexprs-1]->getType());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004371 return Owned(expr);
4372}
4373
Chandler Carruth82214a82011-02-18 23:54:50 +00004374/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004375/// constant and the other is not a pointer. Returns true if a diagnostic is
4376/// emitted.
Chandler Carruth82214a82011-02-18 23:54:50 +00004377bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
4378 SourceLocation QuestionLoc) {
4379 Expr *NullExpr = LHS;
4380 Expr *NonPointerExpr = RHS;
4381 Expr::NullPointerConstantKind NullKind =
4382 NullExpr->isNullPointerConstant(Context,
4383 Expr::NPC_ValueDependentIsNotNull);
4384
4385 if (NullKind == Expr::NPCK_NotNull) {
4386 NullExpr = RHS;
4387 NonPointerExpr = LHS;
4388 NullKind =
4389 NullExpr->isNullPointerConstant(Context,
4390 Expr::NPC_ValueDependentIsNotNull);
4391 }
4392
4393 if (NullKind == Expr::NPCK_NotNull)
4394 return false;
4395
4396 if (NullKind == Expr::NPCK_ZeroInteger) {
4397 // In this case, check to make sure that we got here from a "NULL"
4398 // string in the source code.
4399 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004400 SourceLocation loc = NullExpr->getExprLoc();
4401 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004402 return false;
4403 }
4404
4405 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4406 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4407 << NonPointerExpr->getType() << DiagType
4408 << NonPointerExpr->getSourceRange();
4409 return true;
4410}
4411
Richard Trieu26f96072011-09-02 01:51:02 +00004412/// \brief Return false if the condition expression is valid, true otherwise.
4413static bool checkCondition(Sema &S, Expr *Cond) {
4414 QualType CondTy = Cond->getType();
4415
4416 // C99 6.5.15p2
4417 if (CondTy->isScalarType()) return false;
4418
4419 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4420 if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4421 return false;
4422
4423 // Emit the proper error message.
4424 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4425 diag::err_typecheck_cond_expect_scalar :
4426 diag::err_typecheck_cond_expect_scalar_or_vector)
4427 << CondTy;
4428 return true;
4429}
4430
4431/// \brief Return false if the two expressions can be converted to a vector,
4432/// true otherwise
4433static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4434 ExprResult &RHS,
4435 QualType CondTy) {
4436 // Both operands should be of scalar type.
4437 if (!LHS.get()->getType()->isScalarType()) {
4438 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4439 << CondTy;
4440 return true;
4441 }
4442 if (!RHS.get()->getType()->isScalarType()) {
4443 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4444 << CondTy;
4445 return true;
4446 }
4447
4448 // Implicity convert these scalars to the type of the condition.
4449 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4450 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4451 return false;
4452}
4453
4454/// \brief Handle when one or both operands are void type.
4455static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4456 ExprResult &RHS) {
4457 Expr *LHSExpr = LHS.get();
4458 Expr *RHSExpr = RHS.get();
4459
4460 if (!LHSExpr->getType()->isVoidType())
4461 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4462 << RHSExpr->getSourceRange();
4463 if (!RHSExpr->getType()->isVoidType())
4464 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4465 << LHSExpr->getSourceRange();
4466 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4467 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4468 return S.Context.VoidTy;
4469}
4470
4471/// \brief Return false if the NullExpr can be promoted to PointerTy,
4472/// true otherwise.
4473static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4474 QualType PointerTy) {
4475 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4476 !NullExpr.get()->isNullPointerConstant(S.Context,
4477 Expr::NPC_ValueDependentIsNull))
4478 return true;
4479
4480 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4481 return false;
4482}
4483
4484/// \brief Checks compatibility between two pointers and return the resulting
4485/// type.
4486static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4487 ExprResult &RHS,
4488 SourceLocation Loc) {
4489 QualType LHSTy = LHS.get()->getType();
4490 QualType RHSTy = RHS.get()->getType();
4491
4492 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4493 // Two identical pointers types are always compatible.
4494 return LHSTy;
4495 }
4496
4497 QualType lhptee, rhptee;
4498
4499 // Get the pointee types.
4500 if (LHSTy->isBlockPointerType()) {
4501 lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4502 rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
4503 } else {
4504 lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4505 rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4506 }
4507
4508 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4509 rhptee.getUnqualifiedType())) {
4510 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4511 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4512 << RHS.get()->getSourceRange();
4513 // In this situation, we assume void* type. No especially good
4514 // reason, but this is what gcc does, and we do have to pick
4515 // to get a consistent AST.
4516 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4517 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4518 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4519 return incompatTy;
4520 }
4521
4522 // The pointer types are compatible.
4523 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4524 // differently qualified versions of compatible types, the result type is
4525 // a pointer to an appropriately qualified version of the *composite*
4526 // type.
4527 // FIXME: Need to calculate the composite type.
4528 // FIXME: Need to add qualifiers
4529
4530 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4531 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4532 return LHSTy;
4533}
4534
4535/// \brief Return the resulting type when the operands are both block pointers.
4536static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4537 ExprResult &LHS,
4538 ExprResult &RHS,
4539 SourceLocation Loc) {
4540 QualType LHSTy = LHS.get()->getType();
4541 QualType RHSTy = RHS.get()->getType();
4542
4543 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4544 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4545 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4546 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4547 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4548 return destType;
4549 }
4550 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4551 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4552 << RHS.get()->getSourceRange();
4553 return QualType();
4554 }
4555
4556 // We have 2 block pointer types.
4557 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4558}
4559
4560/// \brief Return the resulting type when the operands are both pointers.
4561static QualType
4562checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4563 ExprResult &RHS,
4564 SourceLocation Loc) {
4565 // get the pointer types
4566 QualType LHSTy = LHS.get()->getType();
4567 QualType RHSTy = RHS.get()->getType();
4568
4569 // get the "pointed to" types
4570 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4571 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4572
4573 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4574 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4575 // Figure out necessary qualifiers (C99 6.5.15p6)
4576 QualType destPointee
4577 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4578 QualType destType = S.Context.getPointerType(destPointee);
4579 // Add qualifiers if necessary.
4580 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4581 // Promote to void*.
4582 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4583 return destType;
4584 }
4585 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4586 QualType destPointee
4587 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4588 QualType destType = S.Context.getPointerType(destPointee);
4589 // Add qualifiers if necessary.
4590 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4591 // Promote to void*.
4592 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4593 return destType;
4594 }
4595
4596 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4597}
4598
4599/// \brief Return false if the first expression is not an integer and the second
4600/// expression is not a pointer, true otherwise.
4601static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4602 Expr* PointerExpr, SourceLocation Loc,
4603 bool isIntFirstExpr) {
4604 if (!PointerExpr->getType()->isPointerType() ||
4605 !Int.get()->getType()->isIntegerType())
4606 return false;
4607
4608 Expr *Expr1 = isIntFirstExpr ? Int.get() : PointerExpr;
4609 Expr *Expr2 = isIntFirstExpr ? PointerExpr : Int.get();
4610
4611 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4612 << Expr1->getType() << Expr2->getType()
4613 << Expr1->getSourceRange() << Expr2->getSourceRange();
4614 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4615 CK_IntegralToPointer);
4616 return true;
4617}
4618
Sebastian Redl28507842009-02-26 14:39:58 +00004619/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4620/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004621/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004622QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4623 ExprResult &RHS, ExprValueKind &VK,
4624 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004625 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004626
John McCallfb8721c2011-04-10 19:13:55 +00004627 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00004628 if (!lhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004629 LHS = move(lhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004630
John McCallfb8721c2011-04-10 19:13:55 +00004631 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00004632 if (!rhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004633 RHS = move(rhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004634
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004635 // C++ is sufficiently different to merit its own checker.
4636 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004637 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004638
4639 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004640 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004641
John Wiegley429bb272011-04-08 18:41:53 +00004642 Cond = UsualUnaryConversions(Cond.take());
4643 if (Cond.isInvalid())
4644 return QualType();
4645 LHS = UsualUnaryConversions(LHS.take());
4646 if (LHS.isInvalid())
4647 return QualType();
4648 RHS = UsualUnaryConversions(RHS.take());
4649 if (RHS.isInvalid())
4650 return QualType();
4651
4652 QualType CondTy = Cond.get()->getType();
4653 QualType LHSTy = LHS.get()->getType();
4654 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004655
Reid Spencer5f016e22007-07-11 17:01:13 +00004656 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00004657 if (checkCondition(*this, Cond.get()))
4658 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004659
Chris Lattner70d67a92008-01-06 22:42:25 +00004660 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004661 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004662 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004663
Nate Begeman6155d732010-09-20 22:41:17 +00004664 // OpenCL: If the condition is a vector, and both operands are scalar,
4665 // attempt to implicity convert them to the vector type to act like the
4666 // built in select.
Richard Trieu26f96072011-09-02 01:51:02 +00004667 if (getLangOptions().OpenCL && CondTy->isVectorType())
4668 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00004669 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00004670
Chris Lattner70d67a92008-01-06 22:42:25 +00004671 // If both operands have arithmetic type, do the usual arithmetic conversions
4672 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004673 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4674 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004675 if (LHS.isInvalid() || RHS.isInvalid())
4676 return QualType();
4677 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004678 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004679
Chris Lattner70d67a92008-01-06 22:42:25 +00004680 // If both operands are the same structure or union type, the result is that
4681 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004682 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4683 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004684 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004685 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004686 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004687 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004688 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004689 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004690
Chris Lattner70d67a92008-01-06 22:42:25 +00004691 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004692 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004693 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004694 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00004695 }
Richard Trieu26f96072011-09-02 01:51:02 +00004696
Steve Naroffb6d54e52008-01-08 01:11:38 +00004697 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4698 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00004699 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4700 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004701
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004702 // All objective-c pointer type analysis is done here.
4703 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4704 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00004705 if (LHS.isInvalid() || RHS.isInvalid())
4706 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004707 if (!compositeType.isNull())
4708 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004709
4710
Steve Naroff7154a772009-07-01 14:36:47 +00004711 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00004712 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4713 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4714 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004715
Steve Naroff7154a772009-07-01 14:36:47 +00004716 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00004717 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4718 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4719 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004720
John McCall404cd162010-11-13 01:35:44 +00004721 // GCC compatibility: soften pointer/integer mismatch. Note that
4722 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00004723 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4724 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00004725 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004726 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4727 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00004728 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004729
Chandler Carruth82214a82011-02-18 23:54:50 +00004730 // Emit a better diagnostic if one of the expressions is a null pointer
4731 // constant and the other is not a pointer type. In this case, the user most
4732 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00004733 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00004734 return QualType();
4735
Chris Lattner70d67a92008-01-06 22:42:25 +00004736 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004737 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00004738 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4739 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004740 return QualType();
4741}
4742
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004743/// FindCompositeObjCPointerType - Helper method to find composite type of
4744/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00004745QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00004746 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00004747 QualType LHSTy = LHS.get()->getType();
4748 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004749
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004750 // Handle things like Class and struct objc_class*. Here we case the result
4751 // to the pseudo-builtin, because that will be implicitly cast back to the
4752 // redefinition type if an attempt is made to access its fields.
4753 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004754 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004755 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004756 return LHSTy;
4757 }
4758 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004759 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004760 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004761 return RHSTy;
4762 }
4763 // And the same for struct objc_object* / id
4764 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004765 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004766 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004767 return LHSTy;
4768 }
4769 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004770 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004771 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004772 return RHSTy;
4773 }
4774 // And the same for struct objc_selector* / SEL
4775 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004776 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004777 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004778 return LHSTy;
4779 }
4780 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004781 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004782 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004783 return RHSTy;
4784 }
4785 // Check constraints for Objective-C object pointers types.
4786 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004787
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004788 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4789 // Two identical object pointer types are always compatible.
4790 return LHSTy;
4791 }
4792 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4793 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4794 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004795
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004796 // If both operands are interfaces and either operand can be
4797 // assigned to the other, use that type as the composite
4798 // type. This allows
4799 // xxx ? (A*) a : (B*) b
4800 // where B is a subclass of A.
4801 //
4802 // Additionally, as for assignment, if either type is 'id'
4803 // allow silent coercion. Finally, if the types are
4804 // incompatible then make sure to use 'id' as the composite
4805 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004806
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004807 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4808 // It could return the composite type.
4809 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4810 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4811 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4812 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4813 } else if ((LHSTy->isObjCQualifiedIdType() ||
4814 RHSTy->isObjCQualifiedIdType()) &&
4815 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4816 // Need to handle "id<xx>" explicitly.
4817 // GCC allows qualified id and any Objective-C type to devolve to
4818 // id. Currently localizing to here until clear this should be
4819 // part of ObjCQualifiedIdTypesAreCompatible.
4820 compositeType = Context.getObjCIdType();
4821 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4822 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004823 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004824 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4825 ;
4826 else {
4827 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4828 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00004829 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004830 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00004831 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4832 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004833 return incompatTy;
4834 }
4835 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00004836 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4837 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004838 return compositeType;
4839 }
4840 // Check Objective-C object pointer types and 'void *'
4841 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4842 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4843 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4844 QualType destPointee
4845 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4846 QualType destType = Context.getPointerType(destPointee);
4847 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004848 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004849 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004850 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004851 return destType;
4852 }
4853 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4854 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4855 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4856 QualType destPointee
4857 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4858 QualType destType = Context.getPointerType(destPointee);
4859 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004860 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004861 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004862 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004863 return destType;
4864 }
4865 return QualType();
4866}
4867
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004868/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004869/// ParenRange in parentheses.
4870static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004871 const PartialDiagnostic &Note,
4872 SourceRange ParenRange) {
4873 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4874 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4875 EndLoc.isValid()) {
4876 Self.Diag(Loc, Note)
4877 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4878 << FixItHint::CreateInsertion(EndLoc, ")");
4879 } else {
4880 // We can't display the parentheses, so just show the bare note.
4881 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004882 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004883}
4884
4885static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4886 return Opc >= BO_Mul && Opc <= BO_Shr;
4887}
4888
Hans Wennborg2f072b42011-06-09 17:06:51 +00004889/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4890/// expression, either using a built-in or overloaded operator,
4891/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
4892static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
4893 Expr **RHS) {
4894 E = E->IgnoreParenImpCasts();
4895 E = E->IgnoreConversionOperator();
4896 E = E->IgnoreParenImpCasts();
4897
4898 // Built-in binary operator.
4899 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4900 if (IsArithmeticOp(OP->getOpcode())) {
4901 *Opcode = OP->getOpcode();
4902 *RHS = OP->getRHS();
4903 return true;
4904 }
4905 }
4906
4907 // Overloaded operator.
4908 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4909 if (Call->getNumArgs() != 2)
4910 return false;
4911
4912 // Make sure this is really a binary operator that is safe to pass into
4913 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4914 OverloadedOperatorKind OO = Call->getOperator();
4915 if (OO < OO_Plus || OO > OO_Arrow)
4916 return false;
4917
4918 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4919 if (IsArithmeticOp(OpKind)) {
4920 *Opcode = OpKind;
4921 *RHS = Call->getArg(1);
4922 return true;
4923 }
4924 }
4925
4926 return false;
4927}
4928
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004929static bool IsLogicOp(BinaryOperatorKind Opc) {
4930 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4931}
4932
Hans Wennborg2f072b42011-06-09 17:06:51 +00004933/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4934/// or is a logical expression such as (x==y) which has int type, but is
4935/// commonly interpreted as boolean.
4936static bool ExprLooksBoolean(Expr *E) {
4937 E = E->IgnoreParenImpCasts();
4938
4939 if (E->getType()->isBooleanType())
4940 return true;
4941 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4942 return IsLogicOp(OP->getOpcode());
4943 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4944 return OP->getOpcode() == UO_LNot;
4945
4946 return false;
4947}
4948
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004949/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4950/// and binary operator are mixed in a way that suggests the programmer assumed
4951/// the conditional operator has higher precedence, for example:
4952/// "int x = a + someBinaryCondition ? 1 : 2".
4953static void DiagnoseConditionalPrecedence(Sema &Self,
4954 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004955 Expr *Condition,
4956 Expr *LHS,
4957 Expr *RHS) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00004958 BinaryOperatorKind CondOpcode;
4959 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004960
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004961 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00004962 return;
4963 if (!ExprLooksBoolean(CondRHS))
4964 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004965
Hans Wennborg2f072b42011-06-09 17:06:51 +00004966 // The condition is an arithmetic binary expression, with a right-
4967 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004968
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004969 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004970 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00004971 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004972
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004973 SuggestParentheses(Self, OpLoc,
4974 Self.PDiag(diag::note_precedence_conditional_silence)
4975 << BinaryOperator::getOpcodeStr(CondOpcode),
4976 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00004977
4978 SuggestParentheses(Self, OpLoc,
4979 Self.PDiag(diag::note_precedence_conditional_first),
4980 SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004981}
4982
Steve Narofff69936d2007-09-16 03:34:24 +00004983/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004984/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00004985ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00004986 SourceLocation ColonLoc,
4987 Expr *CondExpr, Expr *LHSExpr,
4988 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00004989 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4990 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00004991 OpaqueValueExpr *opaqueValue = 0;
4992 Expr *commonExpr = 0;
4993 if (LHSExpr == 0) {
4994 commonExpr = CondExpr;
4995
4996 // We usually want to apply unary conversions *before* saving, except
4997 // in the special case of a C++ l-value conditional.
4998 if (!(getLangOptions().CPlusPlus
4999 && !commonExpr->isTypeDependent()
5000 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5001 && commonExpr->isGLValue()
5002 && commonExpr->isOrdinaryOrBitFieldObject()
5003 && RHSExpr->isOrdinaryOrBitFieldObject()
5004 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005005 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5006 if (commonRes.isInvalid())
5007 return ExprError();
5008 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005009 }
5010
5011 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5012 commonExpr->getType(),
5013 commonExpr->getValueKind(),
5014 commonExpr->getObjectKind());
5015 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005016 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005017
John McCallf89e55a2010-11-18 06:31:45 +00005018 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005019 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005020 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5021 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005022 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005023 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5024 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005025 return ExprError();
5026
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005027 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5028 RHS.get());
5029
John McCall56ca35d2011-02-17 10:25:35 +00005030 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005031 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5032 LHS.take(), ColonLoc,
5033 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005034
5035 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005036 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005037 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5038 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005039}
5040
John McCalle4be87e2011-01-31 23:13:11 +00005041// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005042// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005043// routine is it effectively iqnores the qualifiers on the top level pointee.
5044// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5045// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005046static Sema::AssignConvertType
5047checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5048 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5049 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005050
Reid Spencer5f016e22007-07-11 17:01:13 +00005051 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005052 const Type *lhptee, *rhptee;
5053 Qualifiers lhq, rhq;
5054 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5055 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005056
John McCalle4be87e2011-01-31 23:13:11 +00005057 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005058
5059 // C99 6.5.16.1p1: This following citation is common to constraints
5060 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5061 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005062 Qualifiers lq;
5063
John McCallf85e1932011-06-15 23:02:42 +00005064 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5065 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5066 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5067 // Ignore lifetime for further calculation.
5068 lhq.removeObjCLifetime();
5069 rhq.removeObjCLifetime();
5070 }
5071
John McCall86c05f32011-02-01 00:10:29 +00005072 if (!lhq.compatiblyIncludes(rhq)) {
5073 // Treat address-space mismatches as fatal. TODO: address subspaces
5074 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5075 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5076
John McCallf85e1932011-06-15 23:02:42 +00005077 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005078 // and from void*.
John McCallf85e1932011-06-15 23:02:42 +00005079 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5080 .compatiblyIncludes(
5081 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall22348732011-03-26 02:56:45 +00005082 && (lhptee->isVoidType() || rhptee->isVoidType()))
5083 ; // keep old
5084
John McCallf85e1932011-06-15 23:02:42 +00005085 // Treat lifetime mismatches as fatal.
5086 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5087 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5088
John McCall86c05f32011-02-01 00:10:29 +00005089 // For GCC compatibility, other qualifier mismatches are treated
5090 // as still compatible in C.
5091 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5092 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005093
Mike Stumpeed9cac2009-02-19 03:04:26 +00005094 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5095 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005096 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005097 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005098 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005099 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005100
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005101 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005102 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005103 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005104 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005105
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005106 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005107 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005108 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005109
5110 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005111 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005112 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005113 }
John McCall86c05f32011-02-01 00:10:29 +00005114
Mike Stumpeed9cac2009-02-19 03:04:26 +00005115 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005116 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005117 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5118 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005119 // Check if the pointee types are compatible ignoring the sign.
5120 // We explicitly check for char so that we catch "char" vs
5121 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005122 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005123 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005124 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005125 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005126
Chris Lattner6a2b9262009-10-17 20:33:28 +00005127 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005128 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005129 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005130 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005131
John McCall86c05f32011-02-01 00:10:29 +00005132 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005133 // Types are compatible ignoring the sign. Qualifier incompatibility
5134 // takes priority over sign incompatibility because the sign
5135 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005136 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005137 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005138
John McCalle4be87e2011-01-31 23:13:11 +00005139 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005140 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005141
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005142 // If we are a multi-level pointer, it's possible that our issue is simply
5143 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5144 // the eventual target type is the same and the pointers have the same
5145 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005146 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005147 do {
John McCall86c05f32011-02-01 00:10:29 +00005148 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5149 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005150 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005151
John McCall86c05f32011-02-01 00:10:29 +00005152 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005153 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005154 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005155
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005156 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005157 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005158 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005159 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005160}
5161
John McCalle4be87e2011-01-31 23:13:11 +00005162/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005163/// block pointer types are compatible or whether a block and normal pointer
5164/// are compatible. It is more restrict than comparing two function pointer
5165// types.
John McCalle4be87e2011-01-31 23:13:11 +00005166static Sema::AssignConvertType
5167checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5168 QualType rhsType) {
5169 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5170 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5171
Steve Naroff1c7d0672008-09-04 15:10:53 +00005172 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005173
Steve Naroff1c7d0672008-09-04 15:10:53 +00005174 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCalle4be87e2011-01-31 23:13:11 +00005175 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5176 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005177
John McCalle4be87e2011-01-31 23:13:11 +00005178 // In C++, the types have to match exactly.
5179 if (S.getLangOptions().CPlusPlus)
5180 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005181
John McCalle4be87e2011-01-31 23:13:11 +00005182 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005183
Steve Naroff1c7d0672008-09-04 15:10:53 +00005184 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005185 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5186 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005187
John McCalle4be87e2011-01-31 23:13:11 +00005188 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5189 return Sema::IncompatibleBlockPointer;
5190
Steve Naroff1c7d0672008-09-04 15:10:53 +00005191 return ConvTy;
5192}
5193
John McCalle4be87e2011-01-31 23:13:11 +00005194/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005195/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005196static Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005197checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType,
5198 QualType rhsType) {
John McCalle4be87e2011-01-31 23:13:11 +00005199 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5200 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5201
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005202 if (lhsType->isObjCBuiltinType()) {
5203 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005204 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5205 !rhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005206 return Sema::IncompatiblePointer;
5207 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005208 }
5209 if (rhsType->isObjCBuiltinType()) {
5210 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005211 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5212 !lhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005213 return Sema::IncompatiblePointer;
5214 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005215 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005216 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005217 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005218 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005219 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005220
John McCalle4be87e2011-01-31 23:13:11 +00005221 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5222 return Sema::CompatiblePointerDiscardsQualifiers;
5223
5224 if (S.Context.typesAreCompatible(lhsType, rhsType))
5225 return Sema::Compatible;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005226 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005227 return Sema::IncompatibleObjCQualifiedId;
5228 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005229}
5230
John McCall1c23e912010-11-16 02:32:08 +00005231Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005232Sema::CheckAssignmentConstraints(SourceLocation Loc,
5233 QualType lhsType, QualType rhsType) {
John McCall1c23e912010-11-16 02:32:08 +00005234 // Fake up an opaque expression. We don't actually care about what
5235 // cast operations are required, so if CheckAssignmentConstraints
5236 // adds casts to this they'll be wasted, but fortunately that doesn't
5237 // usually happen on valid code.
Douglas Gregorb608b982011-01-28 02:26:04 +00005238 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005239 ExprResult rhsPtr = &rhs;
John McCall1c23e912010-11-16 02:32:08 +00005240 CastKind K = CK_Invalid;
5241
5242 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5243}
5244
Mike Stumpeed9cac2009-02-19 03:04:26 +00005245/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5246/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005247/// pointers. Here are some objectionable examples that GCC considers warnings:
5248///
5249/// int a, *pint;
5250/// short *pshort;
5251/// struct foo *pfoo;
5252///
5253/// pint = pshort; // warning: assignment from incompatible pointer type
5254/// a = pint; // warning: assignment makes integer from pointer without a cast
5255/// pint = a; // warning: assignment makes pointer from integer without a cast
5256/// pint = pfoo; // warning: assignment from incompatible pointer type
5257///
5258/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005259/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005260///
John McCalldaa8e4e2010-11-15 09:13:47 +00005261/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005262Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00005263Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCalldaa8e4e2010-11-15 09:13:47 +00005264 CastKind &Kind) {
John Wiegley429bb272011-04-08 18:41:53 +00005265 QualType rhsType = rhs.get()->getType();
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005266 QualType origLhsType = lhsType;
John McCall1c23e912010-11-16 02:32:08 +00005267
Chris Lattnerfc144e22008-01-04 23:18:45 +00005268 // Get canonical types. We're not formatting these types, just comparing
5269 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00005270 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5271 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005272
John McCallb6cfa242011-01-31 22:28:28 +00005273 // Common case: no conversion required.
John McCalldaa8e4e2010-11-15 09:13:47 +00005274 if (lhsType == rhsType) {
5275 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005276 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005277 }
5278
Douglas Gregor9d293df2008-10-28 00:22:11 +00005279 // If the left-hand side is a reference type, then we are in a
5280 // (rare!) case where we've allowed the use of references in C,
5281 // e.g., as a parameter type in a built-in function. In this case,
5282 // just make sure that the type referenced is compatible with the
5283 // right-hand side type. The caller is responsible for adjusting
5284 // lhsType so that the resulting expression does not have reference
5285 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005286 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005287 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5288 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005289 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005290 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005291 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005292 }
John McCallb6cfa242011-01-31 22:28:28 +00005293
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005294 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5295 // to the same ExtVector type.
5296 if (lhsType->isExtVectorType()) {
5297 if (rhsType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005298 return Incompatible;
5299 if (rhsType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005300 // CK_VectorSplat does T -> vector T, so first cast to the
5301 // element type.
5302 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5303 if (elType != rhsType) {
5304 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley429bb272011-04-08 18:41:53 +00005305 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005306 }
5307 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005308 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005309 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005310 }
Mike Stump1eb44332009-09-09 15:08:12 +00005311
John McCallb6cfa242011-01-31 22:28:28 +00005312 // Conversions to or from vector type.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005313 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00005314 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005315 // Allow assignments of an AltiVec vector type to an equivalent GCC
5316 // vector type and vice versa
5317 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5318 Kind = CK_BitCast;
5319 return Compatible;
5320 }
5321
Douglas Gregor255210e2010-08-06 10:14:59 +00005322 // If we are allowing lax vector conversions, and LHS and RHS are both
5323 // vectors, the total size only needs to be the same. This is a bitcast;
5324 // no bits are changed but the result type is different.
5325 if (getLangOptions().LaxVectorConversions &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005326 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005327 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005328 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005329 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005330 }
5331 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005332 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005333
John McCallb6cfa242011-01-31 22:28:28 +00005334 // Arithmetic conversions.
Douglas Gregor88623ad2010-05-23 21:53:47 +00005335 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005336 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall1c23e912010-11-16 02:32:08 +00005337 Kind = PrepareScalarCast(*this, rhs, lhsType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005338 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005339 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005340
John McCallb6cfa242011-01-31 22:28:28 +00005341 // Conversions to normal pointers.
5342 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5343 // U* -> T*
John McCalldaa8e4e2010-11-15 09:13:47 +00005344 if (isa<PointerType>(rhsType)) {
5345 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00005346 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005347 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005348
John McCallb6cfa242011-01-31 22:28:28 +00005349 // int -> T*
5350 if (rhsType->isIntegerType()) {
5351 Kind = CK_IntegralToPointer; // FIXME: null?
5352 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005353 }
John McCallb6cfa242011-01-31 22:28:28 +00005354
5355 // C pointers are not compatible with ObjC object pointers,
5356 // with two exceptions:
5357 if (isa<ObjCObjectPointerType>(rhsType)) {
5358 // - conversions to void*
5359 if (lhsPointer->getPointeeType()->isVoidType()) {
5360 Kind = CK_AnyPointerToObjCPointerCast;
5361 return Compatible;
5362 }
5363
5364 // - conversions from 'Class' to the redefinition type
5365 if (rhsType->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005366 Context.hasSameType(lhsType,
5367 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005368 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005369 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005370 }
Steve Naroffb4406862008-09-29 18:10:17 +00005371
John McCallb6cfa242011-01-31 22:28:28 +00005372 Kind = CK_BitCast;
5373 return IncompatiblePointer;
5374 }
5375
5376 // U^ -> void*
5377 if (rhsType->getAs<BlockPointerType>()) {
5378 if (lhsPointer->getPointeeType()->isVoidType()) {
5379 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005380 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005381 }
Steve Naroffb4406862008-09-29 18:10:17 +00005382 }
John McCallb6cfa242011-01-31 22:28:28 +00005383
Steve Naroff1c7d0672008-09-04 15:10:53 +00005384 return Incompatible;
5385 }
5386
John McCallb6cfa242011-01-31 22:28:28 +00005387 // Conversions to block pointers.
Steve Naroff1c7d0672008-09-04 15:10:53 +00005388 if (isa<BlockPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005389 // U^ -> T^
5390 if (rhsType->isBlockPointerType()) {
5391 Kind = CK_AnyPointerToBlockPointerCast;
John McCalle4be87e2011-01-31 23:13:11 +00005392 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00005393 }
5394
5395 // int or null -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00005396 if (rhsType->isIntegerType()) {
5397 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005398 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005399 }
5400
John McCallb6cfa242011-01-31 22:28:28 +00005401 // id -> T^
5402 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5403 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005404 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005405 }
Steve Naroffb4406862008-09-29 18:10:17 +00005406
John McCallb6cfa242011-01-31 22:28:28 +00005407 // void* -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00005408 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005409 if (RHSPT->getPointeeType()->isVoidType()) {
5410 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005411 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005412 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005413
Chris Lattnerfc144e22008-01-04 23:18:45 +00005414 return Incompatible;
5415 }
5416
John McCallb6cfa242011-01-31 22:28:28 +00005417 // Conversions to Objective-C pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00005418 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005419 // A* -> B*
5420 if (rhsType->isObjCObjectPointerType()) {
5421 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005422 Sema::AssignConvertType result =
5423 checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
5424 if (getLangOptions().ObjCAutoRefCount &&
5425 result == Compatible &&
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005426 !CheckObjCARCUnavailableWeakConversion(origLhsType, rhsType))
5427 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005428 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005429 }
5430
5431 // int or null -> A*
John McCalldaa8e4e2010-11-15 09:13:47 +00005432 if (rhsType->isIntegerType()) {
5433 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005434 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005435 }
5436
John McCallb6cfa242011-01-31 22:28:28 +00005437 // In general, C pointers are not compatible with ObjC object pointers,
5438 // with two exceptions:
Steve Naroff14108da2009-07-10 23:34:53 +00005439 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005440 // - conversions from 'void*'
5441 if (rhsType->isVoidPointerType()) {
5442 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005443 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005444 }
5445
5446 // - conversions to 'Class' from its redefinition type
5447 if (lhsType->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005448 Context.hasSameType(rhsType,
5449 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005450 Kind = CK_BitCast;
5451 return Compatible;
5452 }
5453
5454 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005455 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005456 }
John McCallb6cfa242011-01-31 22:28:28 +00005457
5458 // T^ -> A*
5459 if (rhsType->isBlockPointerType()) {
5460 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005461 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005462 }
5463
Steve Naroff14108da2009-07-10 23:34:53 +00005464 return Incompatible;
5465 }
John McCallb6cfa242011-01-31 22:28:28 +00005466
5467 // Conversions from pointers that are not covered by the above.
Chris Lattner78eca282008-04-07 06:49:41 +00005468 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005469 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00005470 if (lhsType == Context.BoolTy) {
5471 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005472 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005473 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005474
John McCallb6cfa242011-01-31 22:28:28 +00005475 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00005476 if (lhsType->isIntegerType()) {
5477 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005478 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005479 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005480
Chris Lattnerfc144e22008-01-04 23:18:45 +00005481 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005482 }
John McCallb6cfa242011-01-31 22:28:28 +00005483
5484 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff14108da2009-07-10 23:34:53 +00005485 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005486 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00005487 if (lhsType == Context.BoolTy) {
5488 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005489 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005490 }
Steve Naroff14108da2009-07-10 23:34:53 +00005491
John McCallb6cfa242011-01-31 22:28:28 +00005492 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00005493 if (lhsType->isIntegerType()) {
5494 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005495 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005496 }
5497
Steve Naroff14108da2009-07-10 23:34:53 +00005498 return Incompatible;
5499 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005500
John McCallb6cfa242011-01-31 22:28:28 +00005501 // struct A -> struct B
Chris Lattnerfc144e22008-01-04 23:18:45 +00005502 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005503 if (Context.typesAreCompatible(lhsType, rhsType)) {
5504 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005505 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005506 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005507 }
John McCallb6cfa242011-01-31 22:28:28 +00005508
Reid Spencer5f016e22007-07-11 17:01:13 +00005509 return Incompatible;
5510}
5511
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005512/// \brief Constructs a transparent union from an expression that is
5513/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005514static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5515 ExprResult &EResult, QualType UnionType,
5516 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005517 // Build an initializer list that designates the appropriate member
5518 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005519 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005520 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00005521 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005522 SourceLocation());
5523 Initializer->setType(UnionType);
5524 Initializer->setInitializedFieldInUnion(Field);
5525
5526 // Build a compound literal constructing a value of the transparent
5527 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005528 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005529 EResult = S.Owned(
5530 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5531 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005532}
5533
5534Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005535Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5536 ExprResult &rExpr) {
John Wiegley429bb272011-04-08 18:41:53 +00005537 QualType FromType = rExpr.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005538
Mike Stump1eb44332009-09-09 15:08:12 +00005539 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005540 // transparent_union GCC extension.
5541 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005542 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005543 return Incompatible;
5544
5545 // The field to initialize within the transparent union.
5546 RecordDecl *UD = UT->getDecl();
5547 FieldDecl *InitField = 0;
5548 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005549 for (RecordDecl::field_iterator it = UD->field_begin(),
5550 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005551 it != itend; ++it) {
5552 if (it->getType()->isPointerType()) {
5553 // If the transparent union contains a pointer type, we allow:
5554 // 1) void pointer
5555 // 2) null pointer constant
5556 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005557 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005558 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005559 InitField = *it;
5560 break;
5561 }
Mike Stump1eb44332009-09-09 15:08:12 +00005562
John Wiegley429bb272011-04-08 18:41:53 +00005563 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005564 Expr::NPC_ValueDependentIsNull)) {
Richard Trieu67e29332011-08-02 04:35:43 +00005565 rExpr = ImpCastExprToType(rExpr.take(), it->getType(),
5566 CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005567 InitField = *it;
5568 break;
5569 }
5570 }
5571
John McCalldaa8e4e2010-11-15 09:13:47 +00005572 CastKind Kind = CK_Invalid;
John Wiegley429bb272011-04-08 18:41:53 +00005573 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005574 == Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +00005575 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005576 InitField = *it;
5577 break;
5578 }
5579 }
5580
5581 if (!InitField)
5582 return Incompatible;
5583
John Wiegley429bb272011-04-08 18:41:53 +00005584 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005585 return Compatible;
5586}
5587
Chris Lattner5cf216b2008-01-04 18:04:52 +00005588Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00005589Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005590 if (getLangOptions().CPlusPlus) {
5591 if (!lhsType->isRecordType()) {
5592 // C++ 5.17p3: If the left operand is not of class type, the
5593 // expression is implicitly converted (C++ 4) to the
5594 // cv-unqualified type of the left operand.
John Wiegley429bb272011-04-08 18:41:53 +00005595 ExprResult Res = PerformImplicitConversion(rExpr.get(),
5596 lhsType.getUnqualifiedType(),
5597 AA_Assigning);
5598 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005599 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005600 Sema::AssignConvertType result = Compatible;
5601 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieu67e29332011-08-02 04:35:43 +00005602 !CheckObjCARCUnavailableWeakConversion(lhsType,
5603 rExpr.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005604 result = IncompatibleObjCWeakRef;
John Wiegley429bb272011-04-08 18:41:53 +00005605 rExpr = move(Res);
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005606 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005607 }
5608
5609 // FIXME: Currently, we fall through and treat C++ classes like C
5610 // structures.
John McCallf6a16482010-12-04 03:47:34 +00005611 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005612
Steve Naroff529a4ad2007-11-27 17:58:44 +00005613 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5614 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00005615 if ((lhsType->isPointerType() ||
5616 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00005617 lhsType->isBlockPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00005618 && rExpr.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00005619 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00005620 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005621 return Compatible;
5622 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005623
Chris Lattner943140e2007-10-16 02:55:40 +00005624 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005625 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005626 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005627 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005628 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005629 // Suppress this for references: C++ 8.5.3p5.
John Wiegley429bb272011-04-08 18:41:53 +00005630 if (!lhsType->isReferenceType()) {
5631 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
5632 if (rExpr.isInvalid())
5633 return Incompatible;
5634 }
Steve Narofff1120de2007-08-24 22:33:52 +00005635
John McCalldaa8e4e2010-11-15 09:13:47 +00005636 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005637 Sema::AssignConvertType result =
John McCall1c23e912010-11-16 02:32:08 +00005638 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005639
Steve Narofff1120de2007-08-24 22:33:52 +00005640 // C99 6.5.16.1p2: The value of the right operand is converted to the
5641 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00005642 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5643 // so that we can use references in built-in functions even in C.
5644 // The getNonReferenceType() call makes sure that the resulting expression
5645 // does not have reference type.
John Wiegley429bb272011-04-08 18:41:53 +00005646 if (result != Incompatible && rExpr.get()->getType() != lhsType)
Richard Trieu67e29332011-08-02 04:35:43 +00005647 rExpr = ImpCastExprToType(rExpr.take(),
5648 lhsType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00005649 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00005650}
5651
Richard Trieu67e29332011-08-02 04:35:43 +00005652QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex,
5653 ExprResult &rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005654 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley429bb272011-04-08 18:41:53 +00005655 << lex.get()->getType() << rex.get()->getType()
5656 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00005657 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005658}
5659
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005660QualType Sema::CheckVectorOperands(ExprResult &lex, ExprResult &rex,
5661 SourceLocation Loc, bool isCompAssign) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00005662 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005663 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00005664 QualType lhsType =
John Wiegley429bb272011-04-08 18:41:53 +00005665 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattnerb77792e2008-07-26 22:17:49 +00005666 QualType rhsType =
John Wiegley429bb272011-04-08 18:41:53 +00005667 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005668
Nate Begemanbe2341d2008-07-14 18:02:46 +00005669 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005670 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00005671 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00005672
Douglas Gregor255210e2010-08-06 10:14:59 +00005673 // Handle the case of equivalent AltiVec and GCC vector types
5674 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5675 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005676 if (lhsType->isExtVectorType()) {
5677 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5678 return lhsType;
5679 }
5680
5681 if (!isCompAssign)
5682 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor255210e2010-08-06 10:14:59 +00005683 return rhsType;
5684 }
5685
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005686 if (getLangOptions().LaxVectorConversions &&
5687 Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) {
5688 // If we are allowing lax vector conversions, and LHS and RHS are both
5689 // vectors, the total size only needs to be the same. This is a
5690 // bitcast; no bits are changed but the result type is different.
5691 // FIXME: Should we really be allowing this?
5692 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5693 return lhsType;
5694 }
5695
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005696 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5697 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5698 bool swapped = false;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005699 if (rhsType->isExtVectorType() && !isCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005700 swapped = true;
5701 std::swap(rex, lex);
5702 std::swap(rhsType, lhsType);
5703 }
Mike Stump1eb44332009-09-09 15:08:12 +00005704
Nate Begemandde25982009-06-28 19:12:57 +00005705 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00005706 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005707 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005708 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005709 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5710 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00005711 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005712 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00005713 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005714 if (swapped) std::swap(rex, lex);
5715 return lhsType;
5716 }
5717 }
5718 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5719 rhsType->isRealFloatingType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005720 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5721 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00005722 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005723 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00005724 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005725 if (swapped) std::swap(rex, lex);
5726 return lhsType;
5727 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00005728 }
5729 }
Mike Stump1eb44332009-09-09 15:08:12 +00005730
Nate Begemandde25982009-06-28 19:12:57 +00005731 // Vectors of different size or scalar and non-ext-vector are errors.
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005732 if (swapped) std::swap(rex, lex);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005733 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley429bb272011-04-08 18:41:53 +00005734 << lex.get()->getType() << rex.get()->getType()
5735 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005736 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00005737}
5738
Richard Trieu67e29332011-08-02 04:35:43 +00005739QualType Sema::CheckMultiplyDivideOperands(ExprResult &lex, ExprResult &rex,
5740 SourceLocation Loc,
5741 bool isCompAssign, bool isDiv) {
5742 if (lex.get()->getType()->isVectorType() ||
5743 rex.get()->getType()->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005744 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005745
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005746 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00005747 if (lex.isInvalid() || rex.isInvalid())
5748 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005749
John Wiegley429bb272011-04-08 18:41:53 +00005750 if (!lex.get()->getType()->isArithmeticType() ||
5751 !rex.get()->getType()->isArithmeticType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00005752 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005753
Chris Lattner7ef655a2010-01-12 21:23:57 +00005754 // Check for division by zero.
5755 if (isDiv &&
Richard Trieu67e29332011-08-02 04:35:43 +00005756 rex.get()->isNullPointerConstant(Context,
5757 Expr::NPC_ValueDependentIsNotNull))
John Wiegley429bb272011-04-08 18:41:53 +00005758 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
Richard Trieu67e29332011-08-02 04:35:43 +00005759 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005760
Chris Lattner7ef655a2010-01-12 21:23:57 +00005761 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005762}
5763
Chris Lattner7ef655a2010-01-12 21:23:57 +00005764QualType Sema::CheckRemainderOperands(
John Wiegley429bb272011-04-08 18:41:53 +00005765 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
Richard Trieu67e29332011-08-02 04:35:43 +00005766 if (lex.get()->getType()->isVectorType() ||
5767 rex.get()->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005768 if (lex.get()->getType()->hasIntegerRepresentation() &&
5769 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005770 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Daniel Dunbar523aa602009-01-05 22:55:36 +00005771 return InvalidOperands(Loc, lex, rex);
5772 }
Steve Naroff90045e82007-07-13 23:32:42 +00005773
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005774 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00005775 if (lex.isInvalid() || rex.isInvalid())
5776 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005777
Richard Trieu67e29332011-08-02 04:35:43 +00005778 if (!lex.get()->getType()->isIntegerType() ||
5779 !rex.get()->getType()->isIntegerType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00005780 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005781
Chris Lattner7ef655a2010-01-12 21:23:57 +00005782 // Check for remainder by zero.
Richard Trieu67e29332011-08-02 04:35:43 +00005783 if (rex.get()->isNullPointerConstant(Context,
5784 Expr::NPC_ValueDependentIsNotNull))
John Wiegley429bb272011-04-08 18:41:53 +00005785 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
5786 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005787
Chris Lattner7ef655a2010-01-12 21:23:57 +00005788 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005789}
5790
Chandler Carruth13b21be2011-06-27 08:02:19 +00005791/// \brief Diagnose invalid arithmetic on two void pointers.
5792static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
5793 Expr *LHS, Expr *RHS) {
5794 S.Diag(Loc, S.getLangOptions().CPlusPlus
5795 ? diag::err_typecheck_pointer_arith_void_type
5796 : diag::ext_gnu_void_ptr)
5797 << 1 /* two pointers */ << LHS->getSourceRange() << RHS->getSourceRange();
5798}
5799
5800/// \brief Diagnose invalid arithmetic on a void pointer.
5801static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5802 Expr *Pointer) {
5803 S.Diag(Loc, S.getLangOptions().CPlusPlus
5804 ? diag::err_typecheck_pointer_arith_void_type
5805 : diag::ext_gnu_void_ptr)
5806 << 0 /* one pointer */ << Pointer->getSourceRange();
5807}
5808
5809/// \brief Diagnose invalid arithmetic on two function pointers.
5810static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5811 Expr *LHS, Expr *RHS) {
5812 assert(LHS->getType()->isAnyPointerType());
5813 assert(RHS->getType()->isAnyPointerType());
5814 S.Diag(Loc, S.getLangOptions().CPlusPlus
5815 ? diag::err_typecheck_pointer_arith_function_type
5816 : diag::ext_gnu_ptr_func_arith)
5817 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5818 // We only show the second type if it differs from the first.
5819 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5820 RHS->getType())
5821 << RHS->getType()->getPointeeType()
5822 << LHS->getSourceRange() << RHS->getSourceRange();
5823}
5824
5825/// \brief Diagnose invalid arithmetic on a function pointer.
5826static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5827 Expr *Pointer) {
5828 assert(Pointer->getType()->isAnyPointerType());
5829 S.Diag(Loc, S.getLangOptions().CPlusPlus
5830 ? diag::err_typecheck_pointer_arith_function_type
5831 : diag::ext_gnu_ptr_func_arith)
5832 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5833 << 0 /* one pointer, so only one type */
5834 << Pointer->getSourceRange();
5835}
5836
Richard Trieu097ecd22011-09-02 02:15:37 +00005837/// \brief Warn if Operand is incomplete pointer type
5838///
5839/// \returns True if pointer has incomplete type
5840static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
5841 Expr *Operand) {
5842 if ((Operand->getType()->isPointerType() &&
5843 !Operand->getType()->isDependentType()) ||
5844 Operand->getType()->isObjCObjectPointerType()) {
5845 QualType PointeeTy = Operand->getType()->getPointeeType();
5846 if (S.RequireCompleteType(
5847 Loc, PointeeTy,
5848 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5849 << PointeeTy << Operand->getSourceRange()))
5850 return true;
5851 }
5852 return false;
5853}
5854
Chandler Carruth13b21be2011-06-27 08:02:19 +00005855/// \brief Check the validity of an arithmetic pointer operand.
5856///
5857/// If the operand has pointer type, this code will check for pointer types
5858/// which are invalid in arithmetic operations. These will be diagnosed
5859/// appropriately, including whether or not the use is supported as an
5860/// extension.
5861///
5862/// \returns True when the operand is valid to use (even if as an extension).
5863static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5864 Expr *Operand) {
5865 if (!Operand->getType()->isAnyPointerType()) return true;
5866
5867 QualType PointeeTy = Operand->getType()->getPointeeType();
5868 if (PointeeTy->isVoidType()) {
5869 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5870 return !S.getLangOptions().CPlusPlus;
5871 }
5872 if (PointeeTy->isFunctionType()) {
5873 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5874 return !S.getLangOptions().CPlusPlus;
5875 }
5876
Richard Trieu097ecd22011-09-02 02:15:37 +00005877 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00005878
5879 return true;
5880}
5881
5882/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5883/// operands.
5884///
5885/// This routine will diagnose any invalid arithmetic on pointer operands much
5886/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5887/// for emitting a single diagnostic even for operations where both LHS and RHS
5888/// are (potentially problematic) pointers.
5889///
5890/// \returns True when the operand is valid to use (even if as an extension).
5891static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
5892 Expr *LHS, Expr *RHS) {
5893 bool isLHSPointer = LHS->getType()->isAnyPointerType();
5894 bool isRHSPointer = RHS->getType()->isAnyPointerType();
5895 if (!isLHSPointer && !isRHSPointer) return true;
5896
5897 QualType LHSPointeeTy, RHSPointeeTy;
5898 if (isLHSPointer) LHSPointeeTy = LHS->getType()->getPointeeType();
5899 if (isRHSPointer) RHSPointeeTy = RHS->getType()->getPointeeType();
5900
5901 // Check for arithmetic on pointers to incomplete types.
5902 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5903 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
5904 if (isLHSVoidPtr || isRHSVoidPtr) {
5905 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHS);
5906 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHS);
5907 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHS, RHS);
5908
5909 return !S.getLangOptions().CPlusPlus;
5910 }
5911
5912 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
5913 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
5914 if (isLHSFuncPtr || isRHSFuncPtr) {
5915 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHS);
5916 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, RHS);
5917 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS, RHS);
5918
5919 return !S.getLangOptions().CPlusPlus;
5920 }
5921
Richard Trieu097ecd22011-09-02 02:15:37 +00005922 if (checkArithmeticIncompletePointerType(S, Loc, LHS)) return false;
5923 if (checkArithmeticIncompletePointerType(S, Loc, RHS)) return false;
5924
Chandler Carruth13b21be2011-06-27 08:02:19 +00005925 return true;
5926}
5927
Richard Trieudb44a6b2011-09-01 22:53:23 +00005928/// \brief Check bad cases where we step over interface counts.
5929static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
5930 SourceLocation OpLoc,
5931 Expr *Op) {
5932 assert(Op->getType()->isAnyPointerType());
5933 QualType PointeeTy = Op->getType()->getPointeeType();
5934 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
5935 return true;
5936
5937 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5938 << PointeeTy << Op->getSourceRange();
5939 return false;
5940}
5941
5942/// \brief Warn when two pointers are incompatible.
5943static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
5944 Expr *LHS, Expr *RHS) {
5945 assert(LHS->getType()->isAnyPointerType());
5946 assert(RHS->getType()->isAnyPointerType());
5947 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5948 << LHS->getType() << RHS->getType() << LHS->getSourceRange()
5949 << RHS->getSourceRange();
5950}
5951
Chris Lattner7ef655a2010-01-12 21:23:57 +00005952QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00005953 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieu67e29332011-08-02 04:35:43 +00005954 if (lex.get()->getType()->isVectorType() ||
5955 rex.get()->getType()->isVectorType()) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005956 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00005957 if (CompLHSTy) *CompLHSTy = compType;
5958 return compType;
5959 }
Steve Naroff49b45262007-07-13 16:58:59 +00005960
Eli Friedmanab3a8522009-03-28 01:22:36 +00005961 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00005962 if (lex.isInvalid() || rex.isInvalid())
5963 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00005964
Reid Spencer5f016e22007-07-11 17:01:13 +00005965 // handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00005966 if (lex.get()->getType()->isArithmeticType() &&
5967 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005968 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005969 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005970 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005971
Eli Friedmand72d16e2008-05-18 18:08:51 +00005972 // Put any potential pointer into PExp
John Wiegley429bb272011-04-08 18:41:53 +00005973 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005974 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00005975 std::swap(PExp, IExp);
5976
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005977 if (PExp->getType()->isAnyPointerType()) {
Eli Friedmand72d16e2008-05-18 18:08:51 +00005978 if (IExp->getType()->isIntegerType()) {
Chandler Carruth13b21be2011-06-27 08:02:19 +00005979 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
5980 return QualType();
5981
Chris Lattnerb5f15622009-04-24 23:50:08 +00005982 // Diagnose bad cases where we step over interface counts.
Richard Trieudb44a6b2011-09-01 22:53:23 +00005983 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
Chris Lattnerb5f15622009-04-24 23:50:08 +00005984 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005985
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005986 // Check array bounds for pointer arithemtic
5987 CheckArrayAccess(PExp, IExp);
5988
Eli Friedmanab3a8522009-03-28 01:22:36 +00005989 if (CompLHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00005990 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman04e83572009-08-20 04:21:42 +00005991 if (LHSTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +00005992 LHSTy = lex.get()->getType();
Eli Friedman04e83572009-08-20 04:21:42 +00005993 if (LHSTy->isPromotableIntegerType())
5994 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005995 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00005996 *CompLHSTy = LHSTy;
5997 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00005998 return PExp->getType();
5999 }
6000 }
6001
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006002 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006003}
6004
Chris Lattnereca7be62008-04-07 05:30:13 +00006005// C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00006006QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Richard Trieu67e29332011-08-02 04:35:43 +00006007 SourceLocation Loc,
6008 QualType* CompLHSTy) {
6009 if (lex.get()->getType()->isVectorType() ||
6010 rex.get()->getType()->isVectorType()) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006011 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006012 if (CompLHSTy) *CompLHSTy = compType;
6013 return compType;
6014 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006015
Eli Friedmanab3a8522009-03-28 01:22:36 +00006016 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00006017 if (lex.isInvalid() || rex.isInvalid())
6018 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006019
Chris Lattner6e4ab612007-12-09 21:53:25 +00006020 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006021
Chris Lattner6e4ab612007-12-09 21:53:25 +00006022 // Handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00006023 if (lex.get()->getType()->isArithmeticType() &&
6024 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006025 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006026 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006027 }
Mike Stump1eb44332009-09-09 15:08:12 +00006028
Chris Lattner6e4ab612007-12-09 21:53:25 +00006029 // Either ptr - int or ptr - ptr.
John Wiegley429bb272011-04-08 18:41:53 +00006030 if (lex.get()->getType()->isAnyPointerType()) {
6031 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006032
Chris Lattnerb5f15622009-04-24 23:50:08 +00006033 // Diagnose bad cases where we step over interface counts.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006034 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, lex.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006035 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006036
Chris Lattner6e4ab612007-12-09 21:53:25 +00006037 // The result type of a pointer-int computation is the pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00006038 if (rex.get()->getType()->isIntegerType()) {
Chandler Carruth13b21be2011-06-27 08:02:19 +00006039 if (!checkArithmeticOpPointerOperand(*this, Loc, lex.get()))
6040 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006041
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006042 Expr *IExpr = rex.get()->IgnoreParenCasts();
6043 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6044 OK_Ordinary, IExpr->getExprLoc());
6045 // Check array bounds for pointer arithemtic
6046 CheckArrayAccess(lex.get()->IgnoreParenCasts(), &negRex);
6047
John Wiegley429bb272011-04-08 18:41:53 +00006048 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
6049 return lex.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006050 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006051
Chris Lattner6e4ab612007-12-09 21:53:25 +00006052 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006053 if (const PointerType *RHSPTy
6054 = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006055 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006056
Eli Friedman88d936b2009-05-16 13:54:38 +00006057 if (getLangOptions().CPlusPlus) {
6058 // Pointee types must be the same: C++ [expr.add]
6059 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudb44a6b2011-09-01 22:53:23 +00006060 diagnosePointerIncompatibility(*this, Loc, lex.get(), rex.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006061 }
6062 } else {
6063 // Pointee types must be compatible C99 6.5.6p3
6064 if (!Context.typesAreCompatible(
6065 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6066 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudb44a6b2011-09-01 22:53:23 +00006067 diagnosePointerIncompatibility(*this, Loc, lex.get(), rex.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006068 return QualType();
6069 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006070 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006071
Chandler Carruth13b21be2011-06-27 08:02:19 +00006072 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6073 lex.get(), rex.get()))
6074 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006075
John Wiegley429bb272011-04-08 18:41:53 +00006076 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006077 return Context.getPointerDiffType();
6078 }
6079 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006080
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006081 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006082}
6083
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006084static bool isScopedEnumerationType(QualType T) {
6085 if (const EnumType *ET = dyn_cast<EnumType>(T))
6086 return ET->getDecl()->isScoped();
6087 return false;
6088}
6089
John Wiegley429bb272011-04-08 18:41:53 +00006090static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth21206d52011-02-23 23:34:11 +00006091 SourceLocation Loc, unsigned Opc,
6092 QualType LHSTy) {
6093 llvm::APSInt Right;
6094 // Check right/shifter operand
Richard Trieu67e29332011-08-02 04:35:43 +00006095 if (rex.get()->isValueDependent() ||
6096 !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006097 return;
6098
6099 if (Right.isNegative()) {
John Wiegley429bb272011-04-08 18:41:53 +00006100 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006101 S.PDiag(diag::warn_shift_negative)
John Wiegley429bb272011-04-08 18:41:53 +00006102 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006103 return;
6104 }
6105 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley429bb272011-04-08 18:41:53 +00006106 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006107 if (Right.uge(LeftBits)) {
John Wiegley429bb272011-04-08 18:41:53 +00006108 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006109 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley429bb272011-04-08 18:41:53 +00006110 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006111 return;
6112 }
6113 if (Opc != BO_Shl)
6114 return;
6115
6116 // When left shifting an ICE which is signed, we can check for overflow which
6117 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6118 // integers have defined behavior modulo one more than the maximum value
6119 // representable in the result type, so never warn for those.
6120 llvm::APSInt Left;
Richard Trieu67e29332011-08-02 04:35:43 +00006121 if (lex.get()->isValueDependent() ||
6122 !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth21206d52011-02-23 23:34:11 +00006123 LHSTy->hasUnsignedIntegerRepresentation())
6124 return;
6125 llvm::APInt ResultBits =
6126 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6127 if (LeftBits.uge(ResultBits))
6128 return;
6129 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6130 Result = Result.shl(Right);
6131
Ted Kremenekfa821382011-06-15 00:54:52 +00006132 // Print the bit representation of the signed integer as an unsigned
6133 // hexadecimal number.
6134 llvm::SmallString<40> HexResult;
6135 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6136
Chandler Carruth21206d52011-02-23 23:34:11 +00006137 // If we are only missing a sign bit, this is less likely to result in actual
6138 // bugs -- if the result is cast back to an unsigned type, it will have the
6139 // expected value. Thus we place this behind a different warning that can be
6140 // turned off separately if needed.
6141 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006142 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6143 << HexResult.str() << LHSTy
John Wiegley429bb272011-04-08 18:41:53 +00006144 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006145 return;
6146 }
6147
6148 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Ted Kremenekfa821382011-06-15 00:54:52 +00006149 << HexResult.str() << Result.getMinSignedBits() << LHSTy
Richard Trieu67e29332011-08-02 04:35:43 +00006150 << Left.getBitWidth() << lex.get()->getSourceRange()
6151 << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006152}
6153
Chris Lattnereca7be62008-04-07 05:30:13 +00006154// C99 6.5.7
Richard Trieu67e29332011-08-02 04:35:43 +00006155QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex,
6156 SourceLocation Loc, unsigned Opc,
6157 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00006158 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley429bb272011-04-08 18:41:53 +00006159 if (!lex.get()->getType()->hasIntegerRepresentation() ||
6160 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006161 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006162
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006163 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6164 // hasIntegerRepresentation() above instead of this.
John Wiegley429bb272011-04-08 18:41:53 +00006165 if (isScopedEnumerationType(lex.get()->getType()) ||
6166 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006167 return InvalidOperands(Loc, lex, rex);
6168 }
6169
Nate Begeman2207d792009-10-25 02:26:48 +00006170 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu67e29332011-08-02 04:35:43 +00006171 if (lex.get()->getType()->isVectorType() ||
6172 rex.get()->getType()->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006173 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006174
Chris Lattnerca5eede2007-12-12 05:47:28 +00006175 // Shifts don't perform usual arithmetic conversions, they just do integer
6176 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006177
John McCall1bc80af2010-12-16 19:28:59 +00006178 // For the LHS, do usual unary conversions, but then reset them away
6179 // if this is a compound assignment.
John Wiegley429bb272011-04-08 18:41:53 +00006180 ExprResult old_lex = lex;
6181 lex = UsualUnaryConversions(lex.take());
6182 if (lex.isInvalid())
6183 return QualType();
6184 QualType LHSTy = lex.get()->getType();
John McCall1bc80af2010-12-16 19:28:59 +00006185 if (isCompAssign) lex = old_lex;
6186
6187 // The RHS is simpler.
John Wiegley429bb272011-04-08 18:41:53 +00006188 rex = UsualUnaryConversions(rex.take());
6189 if (rex.isInvalid())
6190 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006191
Ryan Flynnd0439682009-08-07 16:20:20 +00006192 // Sanity-check shift operands
Chandler Carruth21206d52011-02-23 23:34:11 +00006193 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnd0439682009-08-07 16:20:20 +00006194
Chris Lattnerca5eede2007-12-12 05:47:28 +00006195 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00006196 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006197}
6198
Chandler Carruth99919472010-07-10 12:30:03 +00006199static bool IsWithinTemplateSpecialization(Decl *D) {
6200 if (DeclContext *DC = D->getDeclContext()) {
6201 if (isa<ClassTemplateSpecializationDecl>(DC))
6202 return true;
6203 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6204 return FD->isFunctionTemplateSpecialization();
6205 }
6206 return false;
6207}
6208
Richard Trieue648ac32011-09-02 03:48:46 +00006209/// If two different enums are compared, raise a warning.
6210static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &lex,
6211 ExprResult &rex) {
Richard Trieue648ac32011-09-02 03:48:46 +00006212 QualType LHSStrippedType = lex.get()->IgnoreParenImpCasts()->getType();
6213 QualType RHSStrippedType = rex.get()->IgnoreParenImpCasts()->getType();
6214
6215 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6216 if (!LHSEnumType)
6217 return;
6218 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6219 if (!RHSEnumType)
6220 return;
6221
6222 // Ignore anonymous enums.
6223 if (!LHSEnumType->getDecl()->getIdentifier())
6224 return;
6225 if (!RHSEnumType->getDecl()->getIdentifier())
6226 return;
6227
6228 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6229 return;
6230
6231 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6232 << LHSStrippedType << RHSStrippedType
6233 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6234}
6235
Richard Trieu7be1be02011-09-02 02:55:45 +00006236/// \brief Diagnose bad pointer comparisons.
6237static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
6238 ExprResult &lex, ExprResult &rex,
6239 bool isError) {
6240 S.Diag(Loc, isError ? diag::err_typecheck_comparison_of_distinct_pointers
6241 : diag::ext_typecheck_comparison_of_distinct_pointers)
6242 << lex.get()->getType() << rex.get()->getType()
6243 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6244}
6245
6246/// \brief Returns false if the pointers are converted to a composite type,
6247/// true otherwise.
6248static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu43dff1b2011-09-02 21:44:27 +00006249 ExprResult &lex, ExprResult &rex) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006250 // C++ [expr.rel]p2:
6251 // [...] Pointer conversions (4.10) and qualification
6252 // conversions (4.4) are performed on pointer operands (or on
6253 // a pointer operand and a null pointer constant) to bring
6254 // them to their composite pointer type. [...]
6255 //
6256 // C++ [expr.eq]p1 uses the same notion for (in)equality
6257 // comparisons of pointers.
6258
6259 // C++ [expr.eq]p2:
6260 // In addition, pointers to members can be compared, or a pointer to
6261 // member and a null pointer constant. Pointer to member conversions
6262 // (4.11) and qualification conversions (4.4) are performed to bring
6263 // them to a common type. If one operand is a null pointer constant,
6264 // the common type is the type of the other operand. Otherwise, the
6265 // common type is a pointer to member type similar (4.4) to the type
6266 // of one of the operands, with a cv-qualification signature (4.4)
6267 // that is the union of the cv-qualification signatures of the operand
6268 // types.
6269
6270 QualType lType = lex.get()->getType();
6271 QualType rType = rex.get()->getType();
6272 assert((lType->isPointerType() && rType->isPointerType()) ||
6273 (lType->isMemberPointerType() && rType->isMemberPointerType()));
6274
6275 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006276 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
6277 QualType T = S.FindCompositePointerType(Loc, lex, rex, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006278 if (T.isNull()) {
6279 diagnoseDistinctPointerComparison(S, Loc, lex, rex, /*isError*/true);
6280 return true;
6281 }
6282
6283 if (NonStandardCompositeType)
6284 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6285 << lType << rType << T << lex.get()->getSourceRange()
6286 << rex.get()->getSourceRange();
6287
6288 lex = S.ImpCastExprToType(lex.take(), T, CK_BitCast);
6289 rex = S.ImpCastExprToType(rex.take(), T, CK_BitCast);
6290 return false;
6291}
6292
6293static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
6294 ExprResult &lex,
6295 ExprResult &rex,
6296 bool isError) {
6297 S.Diag(Loc,isError ? diag::err_typecheck_comparison_of_fptr_to_void
6298 : diag::ext_typecheck_comparison_of_fptr_to_void)
6299 << lex.get()->getType() << rex.get()->getType()
6300 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
6301}
6302
Douglas Gregor0c6db942009-05-04 06:07:12 +00006303// C99 6.5.8, C++ [expr.rel]
Richard Trieu67e29332011-08-02 04:35:43 +00006304QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex,
6305 SourceLocation Loc, unsigned OpaqueOpc,
6306 bool isRelational) {
John McCall2de56d12010-08-25 11:45:40 +00006307 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006308
Chris Lattner02dd4b12009-12-05 05:40:13 +00006309 // Handle vector comparisons separately.
Richard Trieu67e29332011-08-02 04:35:43 +00006310 if (lex.get()->getType()->isVectorType() ||
6311 rex.get()->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006312 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006313
John Wiegley429bb272011-04-08 18:41:53 +00006314 QualType lType = lex.get()->getType();
6315 QualType rType = rex.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00006316
John Wiegley429bb272011-04-08 18:41:53 +00006317 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
6318 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006319
Richard Trieue648ac32011-09-02 03:48:46 +00006320 checkEnumComparison(*this, Loc, lex, rex);
Chandler Carruth543cb652011-02-17 08:37:06 +00006321
Douglas Gregor8eee1192010-06-22 22:12:46 +00006322 if (!lType->hasFloatingRepresentation() &&
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006323 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley429bb272011-04-08 18:41:53 +00006324 !lex.get()->getLocStart().isMacroID() &&
6325 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006326 // For non-floating point types, check for self-comparisons of the form
6327 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6328 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006329 //
6330 // NOTE: Don't warn about comparison expressions resulting from macro
6331 // expansion. Also don't warn about comparisons which are only self
6332 // comparisons within a template specialization. The warnings should catch
6333 // obvious cases in the definition of the template anyways. The idea is to
6334 // warn when the typed comparison operator will always evaluate to the same
6335 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006336 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006337 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006338 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006339 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006340 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006341 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006342 << (Opc == BO_EQ
6343 || Opc == BO_LE
6344 || Opc == BO_GE));
Douglas Gregord64fdd02010-06-08 19:50:34 +00006345 } else if (lType->isArrayType() && rType->isArrayType() &&
6346 !DRL->getDecl()->getType()->isReferenceType() &&
6347 !DRR->getDecl()->getType()->isReferenceType()) {
6348 // what is it always going to eval to?
6349 char always_evals_to;
6350 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006351 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006352 always_evals_to = 0; // false
6353 break;
John McCall2de56d12010-08-25 11:45:40 +00006354 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006355 always_evals_to = 1; // true
6356 break;
6357 default:
6358 // best we can say is 'a constant'
6359 always_evals_to = 2; // e.g. array1 <= array2
6360 break;
6361 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006362 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006363 << 1 // array
6364 << always_evals_to);
6365 }
6366 }
Chandler Carruth99919472010-07-10 12:30:03 +00006367 }
Mike Stump1eb44332009-09-09 15:08:12 +00006368
Chris Lattner55660a72009-03-08 19:39:53 +00006369 if (isa<CastExpr>(LHSStripped))
6370 LHSStripped = LHSStripped->IgnoreParenCasts();
6371 if (isa<CastExpr>(RHSStripped))
6372 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006373
Chris Lattner55660a72009-03-08 19:39:53 +00006374 // Warn about comparisons against a string constant (unless the other
6375 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006376 Expr *literalString = 0;
6377 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006378 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006379 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006380 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006381 literalString = lex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006382 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006383 } else if ((isa<StringLiteral>(RHSStripped) ||
6384 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006385 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006386 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006387 literalString = rex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006388 literalStringStripped = RHSStripped;
6389 }
6390
6391 if (literalString) {
6392 std::string resultComparison;
6393 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006394 case BO_LT: resultComparison = ") < 0"; break;
6395 case BO_GT: resultComparison = ") > 0"; break;
6396 case BO_LE: resultComparison = ") <= 0"; break;
6397 case BO_GE: resultComparison = ") >= 0"; break;
6398 case BO_EQ: resultComparison = ") == 0"; break;
6399 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00006400 default: assert(false && "Invalid comparison operator");
6401 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006402
Ted Kremenek351ba912011-02-23 01:52:04 +00006403 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006404 PDiag(diag::warn_stringcompare)
6405 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006406 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006407 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006408 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006409
Douglas Gregord64fdd02010-06-08 19:50:34 +00006410 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieu67e29332011-08-02 04:35:43 +00006411 if (lex.get()->getType()->isArithmeticType() &&
6412 rex.get()->getType()->isArithmeticType()) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006413 UsualArithmeticConversions(lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00006414 if (lex.isInvalid() || rex.isInvalid())
6415 return QualType();
6416 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00006417 else {
John Wiegley429bb272011-04-08 18:41:53 +00006418 lex = UsualUnaryConversions(lex.take());
6419 if (lex.isInvalid())
6420 return QualType();
6421
6422 rex = UsualUnaryConversions(rex.take());
6423 if (rex.isInvalid())
6424 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006425 }
6426
John Wiegley429bb272011-04-08 18:41:53 +00006427 lType = lex.get()->getType();
6428 rType = rex.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006429
Douglas Gregor447b69e2008-11-19 03:25:36 +00006430 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00006431 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00006432
Chris Lattnera5937dd2007-08-26 01:18:55 +00006433 if (isRelational) {
6434 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006435 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006436 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006437 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006438 if (lType->hasFloatingRepresentation())
John Wiegley429bb272011-04-08 18:41:53 +00006439 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006440
Chris Lattnera5937dd2007-08-26 01:18:55 +00006441 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006442 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006443 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006444
John Wiegley429bb272011-04-08 18:41:53 +00006445 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006446 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00006447 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006448 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006449
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006450 // All of the following pointer-related warnings are GCC extensions, except
6451 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00006452 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00006453 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006454 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00006455 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006456 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006457
Douglas Gregor0c6db942009-05-04 06:07:12 +00006458 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00006459 if (LCanPointeeTy == RCanPointeeTy)
6460 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006461 if (!isRelational &&
6462 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6463 // Valid unless comparison between non-null pointer and function pointer
6464 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006465 // In a SFINAE context, we treat this as a hard error to maintain
6466 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006467 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6468 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006469 diagnoseFunctionPointerToVoidComparison(
6470 *this, Loc, lex, rex, /*isError*/ isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006471
6472 if (isSFINAEContext())
6473 return QualType();
6474
John Wiegley429bb272011-04-08 18:41:53 +00006475 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006476 return ResultTy;
6477 }
6478 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006479
Richard Trieu7be1be02011-09-02 02:55:45 +00006480 if (convertPointersToCompositeType(*this, Loc, lex, rex))
Douglas Gregor0c6db942009-05-04 06:07:12 +00006481 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00006482 else
6483 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00006484 }
Eli Friedman3075e762009-08-23 00:27:47 +00006485 // C99 6.5.9p2 and C99 6.5.8p2
6486 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6487 RCanPointeeTy.getUnqualifiedType())) {
6488 // Valid unless a relational comparison of function pointers
6489 if (isRelational && LCanPointeeTy->isFunctionType()) {
6490 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00006491 << lType << rType << lex.get()->getSourceRange()
6492 << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00006493 }
6494 } else if (!isRelational &&
6495 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6496 // Valid unless comparison between non-null pointer and function pointer
6497 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00006498 && !LHSIsNull && !RHSIsNull)
6499 diagnoseFunctionPointerToVoidComparison(*this, Loc, lex, rex,
6500 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00006501 } else {
6502 // Invalid
Richard Trieu7be1be02011-09-02 02:55:45 +00006503 diagnoseDistinctPointerComparison(*this, Loc, lex, rex, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00006504 }
John McCall34d6f932011-03-11 04:25:25 +00006505 if (LCanPointeeTy != RCanPointeeTy) {
6506 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006507 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006508 else
John Wiegley429bb272011-04-08 18:41:53 +00006509 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006510 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00006511 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00006512 }
Mike Stump1eb44332009-09-09 15:08:12 +00006513
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006514 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006515 // Comparison of nullptr_t with itself.
6516 if (lType->isNullPtrType() && rType->isNullPtrType())
6517 return ResultTy;
6518
Mike Stump1eb44332009-09-09 15:08:12 +00006519 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00006520 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00006521 if (RHSIsNull &&
Douglas Gregor17e37c72011-06-01 15:12:24 +00006522 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregor16cd4b72011-06-16 18:52:05 +00006523 (!isRelational &&
6524 (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
John Wiegley429bb272011-04-08 18:41:53 +00006525 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregor443c2122010-08-07 13:36:37 +00006526 lType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006527 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006528 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006529 return ResultTy;
6530 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006531 if (LHSIsNull &&
Douglas Gregor17e37c72011-06-01 15:12:24 +00006532 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregor16cd4b72011-06-16 18:52:05 +00006533 (!isRelational &&
6534 (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
John Wiegley429bb272011-04-08 18:41:53 +00006535 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregor443c2122010-08-07 13:36:37 +00006536 rType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006537 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006538 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006539 return ResultTy;
6540 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006541
6542 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00006543 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00006544 lType->isMemberPointerType() && rType->isMemberPointerType()) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006545 if (convertPointersToCompositeType(*this, Loc, lex, rex))
Douglas Gregor20b3e992009-08-24 17:42:35 +00006546 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00006547 else
6548 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00006549 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006550
6551 // Handle scoped enumeration types specifically, since they don't promote
6552 // to integers.
John Wiegley429bb272011-04-08 18:41:53 +00006553 if (lex.get()->getType()->isEnumeralType() &&
Richard Trieu67e29332011-08-02 04:35:43 +00006554 Context.hasSameUnqualifiedType(lex.get()->getType(),
6555 rex.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00006556 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006557 }
Mike Stump1eb44332009-09-09 15:08:12 +00006558
Steve Naroff1c7d0672008-09-04 15:10:53 +00006559 // Handle block pointer types.
Richard Trieu67e29332011-08-02 04:35:43 +00006560 if (!isRelational && lType->isBlockPointerType() &&
6561 rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006562 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6563 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006564
Steve Naroff1c7d0672008-09-04 15:10:53 +00006565 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00006566 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006567 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieu67e29332011-08-02 04:35:43 +00006568 << lType << rType << lex.get()->getSourceRange()
6569 << rex.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00006570 }
John Wiegley429bb272011-04-08 18:41:53 +00006571 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006572 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006573 }
John Wiegley429bb272011-04-08 18:41:53 +00006574
Steve Naroff59f53942008-09-28 01:11:11 +00006575 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00006576 if (!isRelational
6577 && ((lType->isBlockPointerType() && rType->isPointerType())
6578 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00006579 if (!LHSIsNull && !RHSIsNull) {
John McCall34d6f932011-03-11 04:25:25 +00006580 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006581 ->getPointeeType()->isVoidType())
John McCall34d6f932011-03-11 04:25:25 +00006582 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006583 ->getPointeeType()->isVoidType())))
6584 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieu67e29332011-08-02 04:35:43 +00006585 << lType << rType << lex.get()->getSourceRange()
6586 << rex.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00006587 }
John McCall34d6f932011-03-11 04:25:25 +00006588 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006589 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006590 else
John Wiegley429bb272011-04-08 18:41:53 +00006591 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006592 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00006593 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00006594
John McCall34d6f932011-03-11 04:25:25 +00006595 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
6596 const PointerType *LPT = lType->getAs<PointerType>();
6597 const PointerType *RPT = rType->getAs<PointerType>();
6598 if (LPT || RPT) {
6599 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6600 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006601
Steve Naroffa8069f12008-11-17 19:49:16 +00006602 if (!LPtrToVoid && !RPtrToVoid &&
6603 !Context.typesAreCompatible(lType, rType)) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006604 diagnoseDistinctPointerComparison(*this, Loc, lex, rex,
6605 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00006606 }
John McCall34d6f932011-03-11 04:25:25 +00006607 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006608 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006609 else
John Wiegley429bb272011-04-08 18:41:53 +00006610 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006611 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00006612 }
Steve Naroff14108da2009-07-10 23:34:53 +00006613 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006614 if (!Context.areComparableObjCPointerTypes(lType, rType))
Richard Trieu7be1be02011-09-02 02:55:45 +00006615 diagnoseDistinctPointerComparison(*this, Loc, lex, rex,
6616 /*isError*/false);
John McCall34d6f932011-03-11 04:25:25 +00006617 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006618 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006619 else
John Wiegley429bb272011-04-08 18:41:53 +00006620 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006621 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00006622 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00006623 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006624 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6625 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006626 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006627 bool isError = false;
6628 if ((LHSIsNull && lType->isIntegerType()) ||
6629 (RHSIsNull && rType->isIntegerType())) {
6630 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006631 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006632 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006633 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006634 else if (getLangOptions().CPlusPlus) {
6635 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6636 isError = true;
6637 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006638 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00006639
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006640 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006641 Diag(Loc, DiagID)
Richard Trieu67e29332011-08-02 04:35:43 +00006642 << lType << rType << lex.get()->getSourceRange()
6643 << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006644 if (isError)
6645 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00006646 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006647
6648 if (lType->isIntegerType())
John Wiegley429bb272011-04-08 18:41:53 +00006649 lex = ImpCastExprToType(lex.take(), rType,
John McCall404cd162010-11-13 01:35:44 +00006650 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006651 else
John Wiegley429bb272011-04-08 18:41:53 +00006652 rex = ImpCastExprToType(rex.take(), lType,
John McCall404cd162010-11-13 01:35:44 +00006653 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006654 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006655 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006656
Steve Naroff39218df2008-09-04 16:56:14 +00006657 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00006658 if (!isRelational && RHSIsNull
6659 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006660 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006661 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006662 }
Mike Stumpaf199f32009-05-07 18:43:07 +00006663 if (!isRelational && LHSIsNull
6664 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006665 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006666 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006667 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006668
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006669 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006670}
6671
Nate Begemanbe2341d2008-07-14 18:02:46 +00006672/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00006673/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006674/// like a scalar comparison, a vector comparison produces a vector of integer
6675/// types.
John Wiegley429bb272011-04-08 18:41:53 +00006676QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006677 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006678 bool isRelational) {
6679 // Check to make sure we're operating on vectors of the same type and width,
6680 // Allowing one side to be a scalar of element type.
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006681 QualType vType = CheckVectorOperands(lex, rex, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00006682 if (vType.isNull())
6683 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006684
John Wiegley429bb272011-04-08 18:41:53 +00006685 QualType lType = lex.get()->getType();
6686 QualType rType = rex.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006687
Anton Yartsev7870b132011-03-27 15:36:07 +00006688 // If AltiVec, the comparison results in a numeric type, i.e.
6689 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00006690 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00006691 return Context.getLogicalOperationType();
6692
Nate Begemanbe2341d2008-07-14 18:02:46 +00006693 // For non-floating point types, check for self-comparisons of the form
6694 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6695 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006696 if (!lType->hasFloatingRepresentation()) {
John Wiegley429bb272011-04-08 18:41:53 +00006697 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
6698 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006699 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00006700 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00006701 PDiag(diag::warn_comparison_always)
6702 << 0 // self-
6703 << 2 // "a constant"
6704 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00006705 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006706
Nate Begemanbe2341d2008-07-14 18:02:46 +00006707 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006708 if (!isRelational && lType->hasFloatingRepresentation()) {
6709 assert (rType->hasFloatingRepresentation());
John Wiegley429bb272011-04-08 18:41:53 +00006710 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00006711 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006712
Nate Begemanbe2341d2008-07-14 18:02:46 +00006713 // Return the type for the comparison, which is the same as vector type for
6714 // integer vectors, or an integer type of identical size and number of
6715 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00006716 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00006717 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006718
John McCall183700f2009-09-21 23:43:11 +00006719 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00006720 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00006721 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006722 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00006723 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00006724 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6725
Mike Stumpeed9cac2009-02-19 03:04:26 +00006726 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00006727 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00006728 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6729}
6730
Reid Spencer5f016e22007-07-11 17:01:13 +00006731inline QualType Sema::CheckBitwiseOperands(
John Wiegley429bb272011-04-08 18:41:53 +00006732 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
Richard Trieu67e29332011-08-02 04:35:43 +00006733 if (lex.get()->getType()->isVectorType() ||
6734 rex.get()->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006735 if (lex.get()->getType()->hasIntegerRepresentation() &&
6736 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006737 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00006738
6739 return InvalidOperands(Loc, lex, rex);
6740 }
Steve Naroff90045e82007-07-13 23:32:42 +00006741
John Wiegley429bb272011-04-08 18:41:53 +00006742 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
Richard Trieu67e29332011-08-02 04:35:43 +00006743 QualType compType = UsualArithmeticConversions(lexResult, rexResult,
6744 isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00006745 if (lexResult.isInvalid() || rexResult.isInvalid())
6746 return QualType();
6747 lex = lexResult.take();
6748 rex = rexResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006749
John Wiegley429bb272011-04-08 18:41:53 +00006750 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6751 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006752 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006753 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006754}
6755
6756inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley429bb272011-04-08 18:41:53 +00006757 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00006758
6759 // Diagnose cases where the user write a logical and/or but probably meant a
6760 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6761 // is a constant.
Richard Trieu67e29332011-08-02 04:35:43 +00006762 if (lex.get()->getType()->isIntegerType() &&
6763 !lex.get()->getType()->isBooleanType() &&
John Wiegley429bb272011-04-08 18:41:53 +00006764 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00006765 // Don't warn in macros or template instantiations.
6766 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00006767 // If the RHS can be constant folded, and if it constant folds to something
6768 // that isn't 0 or 1 (which indicate a potential logical operation that
6769 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00006770 // Parens on the RHS are ignored.
Chris Lattnerb7690b42010-07-24 01:10:11 +00006771 Expr::EvalResult Result;
Chandler Carruth0683a142011-05-31 05:41:42 +00006772 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6773 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
6774 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6775 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6776 << rex.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006777 << (Opc == BO_LAnd ? "&&" : "||");
6778 // Suggest replacing the logical operator with the bitwise version
6779 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6780 << (Opc == BO_LAnd ? "&" : "|")
6781 << FixItHint::CreateReplacement(SourceRange(
6782 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6783 getLangOptions())),
6784 Opc == BO_LAnd ? "&" : "|");
6785 if (Opc == BO_LAnd)
6786 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6787 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6788 << FixItHint::CreateRemoval(
6789 SourceRange(
6790 Lexer::getLocForEndOfToken(lex.get()->getLocEnd(),
6791 0, getSourceManager(),
6792 getLangOptions()),
6793 rex.get()->getLocEnd()));
6794 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00006795 }
Chris Lattner90a8f272010-07-13 19:41:32 +00006796
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006797 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00006798 lex = UsualUnaryConversions(lex.take());
6799 if (lex.isInvalid())
6800 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006801
John Wiegley429bb272011-04-08 18:41:53 +00006802 rex = UsualUnaryConversions(rex.take());
6803 if (rex.isInvalid())
6804 return QualType();
6805
Richard Trieu67e29332011-08-02 04:35:43 +00006806 if (!lex.get()->getType()->isScalarType() ||
6807 !rex.get()->getType()->isScalarType())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006808 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006809
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006810 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00006811 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006812
John McCall75f7c0f2010-06-04 00:29:51 +00006813 // The following is safe because we only use this method for
6814 // non-overloadable operands.
6815
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006816 // C++ [expr.log.and]p1
6817 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00006818 // The operands are both contextually converted to type bool.
John Wiegley429bb272011-04-08 18:41:53 +00006819 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
6820 if (lexRes.isInvalid())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006821 return InvalidOperands(Loc, lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00006822 lex = move(lexRes);
6823
6824 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
6825 if (rexRes.isInvalid())
6826 return InvalidOperands(Loc, lex, rex);
6827 rex = move(rexRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006828
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006829 // C++ [expr.log.and]p2
6830 // C++ [expr.log.or]p2
6831 // The result is a bool.
6832 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006833}
6834
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006835/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6836/// is a read-only property; return true if so. A readonly property expression
6837/// depends on various declarations and thus must be treated specially.
6838///
Mike Stump1eb44332009-09-09 15:08:12 +00006839static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006840 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6841 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00006842 if (PropExpr->isImplicitProperty()) return false;
6843
6844 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6845 QualType BaseType = PropExpr->isSuperReceiver() ?
6846 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00006847 PropExpr->getBase()->getType();
6848
John McCall12f78a62010-12-02 01:19:52 +00006849 if (const ObjCObjectPointerType *OPT =
6850 BaseType->getAsObjCInterfacePointerType())
6851 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6852 if (S.isPropertyReadonly(PDecl, IFace))
6853 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006854 }
6855 return false;
6856}
6857
Fariborz Jahanian14086762011-03-28 23:47:18 +00006858static bool IsConstProperty(Expr *E, Sema &S) {
6859 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6860 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6861 if (PropExpr->isImplicitProperty()) return false;
6862
6863 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6864 QualType T = PDecl->getType();
6865 if (T->isReferenceType())
Fariborz Jahanian61750f22011-03-30 16:59:30 +00006866 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanian14086762011-03-28 23:47:18 +00006867 CanQualType CT = S.Context.getCanonicalType(T);
6868 return CT.isConstQualified();
6869 }
6870 return false;
6871}
6872
Fariborz Jahanian077f4902011-03-26 19:48:30 +00006873static bool IsReadonlyMessage(Expr *E, Sema &S) {
6874 if (E->getStmtClass() != Expr::MemberExprClass)
6875 return false;
6876 const MemberExpr *ME = cast<MemberExpr>(E);
6877 NamedDecl *Member = ME->getMemberDecl();
6878 if (isa<FieldDecl>(Member)) {
6879 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6880 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6881 return false;
6882 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6883 }
6884 return false;
6885}
6886
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006887/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6888/// emit an error and return true. If so, return false.
6889static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006890 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00006891 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006892 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006893 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6894 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian14086762011-03-28 23:47:18 +00006895 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6896 IsLV = Expr::MLV_Valid;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00006897 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6898 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006899 if (IsLV == Expr::MLV_Valid)
6900 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006901
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006902 unsigned Diag = 0;
6903 bool NeedType = false;
6904 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00006905 case Expr::MLV_ConstQualified:
6906 Diag = diag::err_typecheck_assign_const;
6907
John McCall7acddac2011-06-17 06:42:21 +00006908 // In ARC, use some specialized diagnostics for occasions where we
6909 // infer 'const'. These are always pseudo-strong variables.
John McCallf85e1932011-06-15 23:02:42 +00006910 if (S.getLangOptions().ObjCAutoRefCount) {
6911 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6912 if (declRef && isa<VarDecl>(declRef->getDecl())) {
6913 VarDecl *var = cast<VarDecl>(declRef->getDecl());
6914
John McCall7acddac2011-06-17 06:42:21 +00006915 // Use the normal diagnostic if it's pseudo-__strong but the
6916 // user actually wrote 'const'.
6917 if (var->isARCPseudoStrong() &&
6918 (!var->getTypeSourceInfo() ||
6919 !var->getTypeSourceInfo()->getType().isConstQualified())) {
6920 // There are two pseudo-strong cases:
6921 // - self
John McCallf85e1932011-06-15 23:02:42 +00006922 ObjCMethodDecl *method = S.getCurMethodDecl();
6923 if (method && var == method->getSelfDecl())
6924 Diag = diag::err_typecheck_arr_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00006925
6926 // - fast enumeration variables
6927 else
John McCallf85e1932011-06-15 23:02:42 +00006928 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00006929
John McCallf85e1932011-06-15 23:02:42 +00006930 SourceRange Assign;
6931 if (Loc != OrigLoc)
6932 Assign = SourceRange(OrigLoc, OrigLoc);
6933 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6934 // We need to preserve the AST regardless, so migration tool
6935 // can do its job.
6936 return false;
6937 }
6938 }
6939 }
6940
6941 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006942 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006943 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6944 NeedType = true;
6945 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006946 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006947 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6948 NeedType = true;
6949 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00006950 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006951 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6952 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00006953 case Expr::MLV_Valid:
6954 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00006955 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00006956 case Expr::MLV_MemberFunction:
6957 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006958 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6959 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006960 case Expr::MLV_IncompleteType:
6961 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00006962 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006963 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00006964 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00006965 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006966 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6967 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00006968 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006969 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6970 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00006971 case Expr::MLV_ReadonlyProperty:
6972 Diag = diag::error_readonly_property_assignment;
6973 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00006974 case Expr::MLV_NoSetterProperty:
6975 Diag = diag::error_nosetter_property_assignment;
6976 break;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00006977 case Expr::MLV_InvalidMessageExpression:
6978 Diag = diag::error_readonly_message_assignment;
6979 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00006980 case Expr::MLV_SubObjCPropertySetting:
6981 Diag = diag::error_no_subobject_property_setting;
6982 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006983 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00006984
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006985 SourceRange Assign;
6986 if (Loc != OrigLoc)
6987 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006988 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006989 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006990 else
Mike Stump1eb44332009-09-09 15:08:12 +00006991 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006992 return true;
6993}
6994
6995
6996
6997// C99 6.5.16.1
John Wiegley429bb272011-04-08 18:41:53 +00006998QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006999 SourceLocation Loc,
7000 QualType CompoundType) {
7001 // Verify that LHS is a modifiable lvalue, and emit error if not.
7002 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007003 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007004
7005 QualType LHSType = LHS->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007006 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7007 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007008 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007009 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007010 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007011 // Simple assignment "x = y".
John Wiegley429bb272011-04-08 18:41:53 +00007012 if (LHS->getObjectKind() == OK_ObjCProperty) {
7013 ExprResult LHSResult = Owned(LHS);
7014 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7015 if (LHSResult.isInvalid())
7016 return QualType();
7017 LHS = LHSResult.take();
7018 }
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007019 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007020 if (RHS.isInvalid())
7021 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007022 // Special case of NSObject attributes on c-style pointer types.
7023 if (ConvTy == IncompatiblePointer &&
7024 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007025 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007026 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007027 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007028 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007029
John McCallf89e55a2010-11-18 06:31:45 +00007030 if (ConvTy == Compatible &&
7031 getLangOptions().ObjCNonFragileABI &&
7032 LHSType->isObjCObjectType())
7033 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7034 << LHSType;
7035
Chris Lattner2c156472008-08-21 18:04:13 +00007036 // If the RHS is a unary plus or minus, check to see if they = and + are
7037 // right next to each other. If so, the user may have typo'd "x =+ 4"
7038 // instead of "x += 4".
John Wiegley429bb272011-04-08 18:41:53 +00007039 Expr *RHSCheck = RHS.get();
Chris Lattner2c156472008-08-21 18:04:13 +00007040 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7041 RHSCheck = ICE->getSubExpr();
7042 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007043 if ((UO->getOpcode() == UO_Plus ||
7044 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007045 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007046 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00007047 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7048 // And there is a space or other character before the subexpr of the
7049 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00007050 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7051 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007052 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007053 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007054 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007055 }
Chris Lattner2c156472008-08-21 18:04:13 +00007056 }
John McCallf85e1932011-06-15 23:02:42 +00007057
7058 if (ConvTy == Compatible) {
7059 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
7060 checkRetainCycles(LHS, RHS.get());
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007061 else if (getLangOptions().ObjCAutoRefCount)
7062 checkUnsafeExprAssigns(Loc, LHS, RHS.get());
John McCallf85e1932011-06-15 23:02:42 +00007063 }
Chris Lattner2c156472008-08-21 18:04:13 +00007064 } else {
7065 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007066 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007067 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007068
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007069 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007070 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007071 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007072
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +00007073 CheckForNullPointerDereference(*this, LHS);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007074
Reid Spencer5f016e22007-07-11 17:01:13 +00007075 // C99 6.5.16p3: The type of an assignment expression is the type of the
7076 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007077 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007078 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7079 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007080 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007081 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00007082 return (getLangOptions().CPlusPlus
7083 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007084}
7085
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007086// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007087static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007088 SourceLocation Loc) {
John Wiegley429bb272011-04-08 18:41:53 +00007089 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00007090
John McCallfb8721c2011-04-10 19:13:55 +00007091 LHS = S.CheckPlaceholderExpr(LHS.take());
7092 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007093 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007094 return QualType();
7095
John McCallcf2e5062010-10-12 07:14:40 +00007096 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7097 // operands, but not unary promotions.
7098 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007099
John McCallf6a16482010-12-04 03:47:34 +00007100 // So we treat the LHS as a ignored value, and in C++ we allow the
7101 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007102 LHS = S.IgnoredValueConversions(LHS.take());
7103 if (LHS.isInvalid())
7104 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007105
7106 if (!S.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007107 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7108 if (RHS.isInvalid())
7109 return QualType();
7110 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007111 S.RequireCompleteType(Loc, RHS.get()->getType(),
7112 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007113 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007114
John Wiegley429bb272011-04-08 18:41:53 +00007115 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007116}
7117
Steve Naroff49b45262007-07-13 16:58:59 +00007118/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7119/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007120static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7121 ExprValueKind &VK,
7122 SourceLocation OpLoc,
7123 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007124 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007125 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007126
Chris Lattner3528d352008-11-21 07:05:48 +00007127 QualType ResType = Op->getType();
7128 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007129
John McCall09431682010-11-18 19:01:18 +00007130 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007131 // Decrement of bool is not allowed.
7132 if (!isInc) {
John McCall09431682010-11-18 19:01:18 +00007133 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007134 return QualType();
7135 }
7136 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007137 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007138 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007139 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007140 } else if (ResType->isAnyPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007141 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007142 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007143 return QualType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00007144
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007145 // Diagnose bad cases where we step over interface counts.
Richard Trieudb44a6b2011-09-01 22:53:23 +00007146 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007147 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007148 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007149 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007150 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007151 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007152 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007153 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007154 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007155 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7156 isInc, isPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00007157 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7158 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007159 } else {
John McCall09431682010-11-18 19:01:18 +00007160 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00007161 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007162 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007163 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007164 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007165 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007166 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007167 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007168 // In C++, a prefix increment is the same type as the operand. Otherwise
7169 // (in C or with postfix), the increment is the unqualified type of the
7170 // operand.
John McCall09431682010-11-18 19:01:18 +00007171 if (isPrefix && S.getLangOptions().CPlusPlus) {
7172 VK = VK_LValue;
7173 return ResType;
7174 } else {
7175 VK = VK_RValue;
7176 return ResType.getUnqualifiedType();
7177 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007178}
7179
John Wiegley429bb272011-04-08 18:41:53 +00007180ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCallf6a16482010-12-04 03:47:34 +00007181 assert(E->getValueKind() == VK_LValue &&
7182 E->getObjectKind() == OK_ObjCProperty);
7183 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7184
Douglas Gregor926df6c2011-06-11 01:09:30 +00007185 QualType T = E->getType();
7186 QualType ReceiverType;
7187 if (PRE->isObjectReceiver())
7188 ReceiverType = PRE->getBase()->getType();
7189 else if (PRE->isSuperReceiver())
7190 ReceiverType = PRE->getSuperReceiverType();
7191 else
7192 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7193
John McCallf6a16482010-12-04 03:47:34 +00007194 ExprValueKind VK = VK_RValue;
7195 if (PRE->isImplicitProperty()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00007196 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007197 PRE->getImplicitPropertyGetter()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00007198 T = getMessageSendResultType(ReceiverType, GetterMethod,
7199 PRE->isClassReceiver(),
7200 PRE->isSuperReceiver());
7201 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007202 }
7203 else {
7204 Diag(PRE->getLocation(), diag::err_getter_not_found)
7205 << PRE->getBase()->getType();
7206 }
John McCallf6a16482010-12-04 03:47:34 +00007207 }
Douglas Gregor926df6c2011-06-11 01:09:30 +00007208
7209 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCallf6a16482010-12-04 03:47:34 +00007210 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00007211
7212 ExprResult Result = MaybeBindToTemporary(E);
7213 if (!Result.isInvalid())
7214 E = Result.take();
John Wiegley429bb272011-04-08 18:41:53 +00007215
7216 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00007217}
7218
Richard Trieu67e29332011-08-02 04:35:43 +00007219void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7220 QualType &LHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00007221 assert(LHS.get()->getValueKind() == VK_LValue &&
7222 LHS.get()->getObjectKind() == OK_ObjCProperty);
7223 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCallf6a16482010-12-04 03:47:34 +00007224
John McCallf85e1932011-06-15 23:02:42 +00007225 bool Consumed = false;
7226
John Wiegley429bb272011-04-08 18:41:53 +00007227 if (PropRef->isImplicitProperty()) {
John McCallf6a16482010-12-04 03:47:34 +00007228 // If using property-dot syntax notation for assignment, and there is a
7229 // setter, RHS expression is being passed to the setter argument. So,
7230 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley429bb272011-04-08 18:41:53 +00007231 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCallf6a16482010-12-04 03:47:34 +00007232 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7233 LHSTy = (*P)->getType();
John McCallf85e1932011-06-15 23:02:42 +00007234 Consumed = (getLangOptions().ObjCAutoRefCount &&
7235 (*P)->hasAttr<NSConsumedAttr>());
John McCallf6a16482010-12-04 03:47:34 +00007236
7237 // Otherwise, if the getter returns an l-value, just call that.
7238 } else {
John Wiegley429bb272011-04-08 18:41:53 +00007239 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCallf6a16482010-12-04 03:47:34 +00007240 ExprValueKind VK = Expr::getValueKindForType(Result);
7241 if (VK == VK_LValue) {
John Wiegley429bb272011-04-08 18:41:53 +00007242 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7243 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCallf6a16482010-12-04 03:47:34 +00007244 return;
John McCall12f78a62010-12-02 01:19:52 +00007245 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007246 }
John McCallf85e1932011-06-15 23:02:42 +00007247 } else if (getLangOptions().ObjCAutoRefCount) {
7248 const ObjCMethodDecl *setter
7249 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7250 if (setter) {
7251 ObjCMethodDecl::param_iterator P = setter->param_begin();
7252 LHSTy = (*P)->getType();
7253 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7254 }
John McCallf6a16482010-12-04 03:47:34 +00007255 }
7256
John McCallf85e1932011-06-15 23:02:42 +00007257 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7258 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007259 InitializedEntity Entity =
John McCallf85e1932011-06-15 23:02:42 +00007260 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley429bb272011-04-08 18:41:53 +00007261 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCallf85e1932011-06-15 23:02:42 +00007262 if (!ArgE.isInvalid()) {
John Wiegley429bb272011-04-08 18:41:53 +00007263 RHS = ArgE;
John McCallf85e1932011-06-15 23:02:42 +00007264 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7265 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7266 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007267 }
7268}
7269
7270
Anders Carlsson369dee42008-02-01 07:15:58 +00007271/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007272/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007273/// where the declaration is needed for type checking. We only need to
7274/// handle cases when the expression references a function designator
7275/// or is an lvalue. Here are some examples:
7276/// - &(x) => x
7277/// - &*****f => f for f a function designator.
7278/// - &s.xx => s
7279/// - &s.zz[1].yy -> s, if zz is an array
7280/// - *(x + 1) -> x, if x is an array
7281/// - &"123"[2] -> 0
7282/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007283static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007284 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007285 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007286 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007287 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007288 // If this is an arrow operator, the address is an offset from
7289 // the base's value, so the object the base refers to is
7290 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007291 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007292 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007293 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007294 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007295 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007296 // FIXME: This code shouldn't be necessary! We should catch the implicit
7297 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007298 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7299 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7300 if (ICE->getSubExpr()->getType()->isArrayType())
7301 return getPrimaryDecl(ICE->getSubExpr());
7302 }
7303 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007304 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007305 case Stmt::UnaryOperatorClass: {
7306 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007307
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007308 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007309 case UO_Real:
7310 case UO_Imag:
7311 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007312 return getPrimaryDecl(UO->getSubExpr());
7313 default:
7314 return 0;
7315 }
7316 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007317 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007318 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007319 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007320 // If the result of an implicit cast is an l-value, we care about
7321 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007322 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007323 default:
7324 return 0;
7325 }
7326}
7327
Richard Trieu09a26ad2011-09-02 00:47:55 +00007328/// \brief Diagnose invalid operand for address of operations.
7329///
7330/// \param Type The type of operand which cannot have its address taken.
7331/// 0:bit-field 1:vector element 2:property expression 3:register variable
7332static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7333 Expr *E, unsigned Type) {
7334 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7335}
7336
Reid Spencer5f016e22007-07-11 17:01:13 +00007337/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007338/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007339/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007340/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007341/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007342/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007343/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00007344static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7345 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00007346 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007347 return S.Context.DependentTy;
7348 if (OrigOp->getType() == S.Context.OverloadTy)
7349 return S.Context.OverloadTy;
John McCall755d8492011-04-12 00:42:48 +00007350 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7351 return S.Context.UnknownAnyTy;
John McCall864c0412011-04-26 20:42:42 +00007352 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7353 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7354 << OrigOp->getSourceRange();
7355 return QualType();
7356 }
John McCall9c72c602010-08-27 09:08:28 +00007357
John McCall755d8492011-04-12 00:42:48 +00007358 assert(!OrigOp->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00007359
John McCall9c72c602010-08-27 09:08:28 +00007360 // Make sure to ignore parentheses in subsequent checks
7361 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007362
John McCall09431682010-11-18 19:01:18 +00007363 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007364 // Implement C99-only parts of addressof rules.
7365 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007366 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007367 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7368 // (assuming the deref expression is valid).
7369 return uOp->getSubExpr()->getType();
7370 }
7371 // Technically, there should be a check for array subscript
7372 // expressions here, but the result of one is always an lvalue anyway.
7373 }
John McCall5808ce42011-02-03 08:15:49 +00007374 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007375 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007376
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007377 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007378 bool sfinae = S.isSFINAEContext();
7379 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7380 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007381 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007382 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007383 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007384 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007385 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007386 } else if (lval == Expr::LV_MemberFunction) {
7387 // If it's an instance method, make a member pointer.
7388 // The expression must have exactly the form &A::foo.
7389
7390 // If the underlying expression isn't a decl ref, give up.
7391 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007392 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007393 << OrigOp->getSourceRange();
7394 return QualType();
7395 }
7396 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7397 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7398
7399 // The id-expression was parenthesized.
7400 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00007401 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007402 << OrigOp->getSourceRange();
7403
7404 // The method was named without a qualifier.
7405 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007406 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007407 << op->getSourceRange();
7408 }
7409
John McCall09431682010-11-18 19:01:18 +00007410 return S.Context.getMemberPointerType(op->getType(),
7411 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007412 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007413 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007414 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007415 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00007416 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00007417 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00007418 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007419 return QualType();
7420 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007421 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007422 // The operand cannot be a bit-field
Richard Trieu09a26ad2011-09-02 00:47:55 +00007423 diagnoseAddressOfInvalidType(S, OpLoc, op, /*bit-field*/ 0);
7424 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007425 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007426 // The operand cannot be an element of a vector
Richard Trieu09a26ad2011-09-02 00:47:55 +00007427 diagnoseAddressOfInvalidType(S, OpLoc, op, /*vector element*/ 1);
Steve Naroffbcb2b612008-02-29 23:30:25 +00007428 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007429 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007430 // cannot take address of a property expression.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007431 diagnoseAddressOfInvalidType(S, OpLoc, op, /*property expression*/ 2);
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007432 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007433 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007434 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007435 // with the register storage-class specifier.
7436 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00007437 // in C++ it is not error to take address of a register
7438 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00007439 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00007440 !S.getLangOptions().CPlusPlus) {
Richard Trieu09a26ad2011-09-02 00:47:55 +00007441 diagnoseAddressOfInvalidType(S, OpLoc, op, /*register variable*/ 3);
Reid Spencer5f016e22007-07-11 17:01:13 +00007442 return QualType();
7443 }
John McCallba135432009-11-21 08:51:07 +00007444 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00007445 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00007446 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00007447 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00007448 // Could be a pointer to member, though, if there is an explicit
7449 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00007450 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00007451 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007452 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00007453 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00007454 S.Diag(OpLoc,
7455 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00007456 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007457 return QualType();
7458 }
Mike Stump1eb44332009-09-09 15:08:12 +00007459
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00007460 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7461 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00007462 return S.Context.getMemberPointerType(op->getType(),
7463 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007464 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00007465 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00007466 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00007467 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00007468 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00007469
Eli Friedman441cf102009-05-16 23:27:50 +00007470 if (lval == Expr::LV_IncompleteVoidType) {
7471 // Taking the address of a void variable is technically illegal, but we
7472 // allow it in cases which are otherwise valid.
7473 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00007474 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00007475 }
7476
Reid Spencer5f016e22007-07-11 17:01:13 +00007477 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00007478 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00007479 return S.Context.getObjCObjectPointerType(op->getType());
7480 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007481}
7482
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007483/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00007484static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7485 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00007486 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007487 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007488
John Wiegley429bb272011-04-08 18:41:53 +00007489 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7490 if (ConvResult.isInvalid())
7491 return QualType();
7492 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007493 QualType OpTy = Op->getType();
7494 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00007495
7496 if (isa<CXXReinterpretCastExpr>(Op)) {
7497 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7498 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7499 Op->getSourceRange());
7500 }
7501
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007502 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7503 // is an incomplete type or void. It would be possible to warn about
7504 // dereferencing a void pointer, but it's completely well-defined, and such a
7505 // warning is unlikely to catch any mistakes.
7506 if (const PointerType *PT = OpTy->getAs<PointerType>())
7507 Result = PT->getPointeeType();
7508 else if (const ObjCObjectPointerType *OPT =
7509 OpTy->getAs<ObjCObjectPointerType>())
7510 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00007511 else {
John McCallfb8721c2011-04-10 19:13:55 +00007512 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007513 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007514 if (PR.take() != Op)
7515 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007516 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007517
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007518 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00007519 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007520 << OpTy << Op->getSourceRange();
7521 return QualType();
7522 }
John McCall09431682010-11-18 19:01:18 +00007523
7524 // Dereferences are usually l-values...
7525 VK = VK_LValue;
7526
7527 // ...except that certain expressions are never l-values in C.
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00007528 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00007529 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007530
7531 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00007532}
7533
John McCall2de56d12010-08-25 11:45:40 +00007534static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007535 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007536 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007537 switch (Kind) {
7538 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00007539 case tok::periodstar: Opc = BO_PtrMemD; break;
7540 case tok::arrowstar: Opc = BO_PtrMemI; break;
7541 case tok::star: Opc = BO_Mul; break;
7542 case tok::slash: Opc = BO_Div; break;
7543 case tok::percent: Opc = BO_Rem; break;
7544 case tok::plus: Opc = BO_Add; break;
7545 case tok::minus: Opc = BO_Sub; break;
7546 case tok::lessless: Opc = BO_Shl; break;
7547 case tok::greatergreater: Opc = BO_Shr; break;
7548 case tok::lessequal: Opc = BO_LE; break;
7549 case tok::less: Opc = BO_LT; break;
7550 case tok::greaterequal: Opc = BO_GE; break;
7551 case tok::greater: Opc = BO_GT; break;
7552 case tok::exclaimequal: Opc = BO_NE; break;
7553 case tok::equalequal: Opc = BO_EQ; break;
7554 case tok::amp: Opc = BO_And; break;
7555 case tok::caret: Opc = BO_Xor; break;
7556 case tok::pipe: Opc = BO_Or; break;
7557 case tok::ampamp: Opc = BO_LAnd; break;
7558 case tok::pipepipe: Opc = BO_LOr; break;
7559 case tok::equal: Opc = BO_Assign; break;
7560 case tok::starequal: Opc = BO_MulAssign; break;
7561 case tok::slashequal: Opc = BO_DivAssign; break;
7562 case tok::percentequal: Opc = BO_RemAssign; break;
7563 case tok::plusequal: Opc = BO_AddAssign; break;
7564 case tok::minusequal: Opc = BO_SubAssign; break;
7565 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7566 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7567 case tok::ampequal: Opc = BO_AndAssign; break;
7568 case tok::caretequal: Opc = BO_XorAssign; break;
7569 case tok::pipeequal: Opc = BO_OrAssign; break;
7570 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007571 }
7572 return Opc;
7573}
7574
John McCall2de56d12010-08-25 11:45:40 +00007575static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007576 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007577 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007578 switch (Kind) {
7579 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00007580 case tok::plusplus: Opc = UO_PreInc; break;
7581 case tok::minusminus: Opc = UO_PreDec; break;
7582 case tok::amp: Opc = UO_AddrOf; break;
7583 case tok::star: Opc = UO_Deref; break;
7584 case tok::plus: Opc = UO_Plus; break;
7585 case tok::minus: Opc = UO_Minus; break;
7586 case tok::tilde: Opc = UO_Not; break;
7587 case tok::exclaim: Opc = UO_LNot; break;
7588 case tok::kw___real: Opc = UO_Real; break;
7589 case tok::kw___imag: Opc = UO_Imag; break;
7590 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007591 }
7592 return Opc;
7593}
7594
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007595/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7596/// This warning is only emitted for builtin assignment operations. It is also
7597/// suppressed in the event of macro expansions.
7598static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7599 SourceLocation OpLoc) {
7600 if (!S.ActiveTemplateInstantiations.empty())
7601 return;
7602 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7603 return;
7604 lhs = lhs->IgnoreParenImpCasts();
7605 rhs = rhs->IgnoreParenImpCasts();
7606 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7607 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7608 if (!LeftDeclRef || !RightDeclRef ||
7609 LeftDeclRef->getLocation().isMacroID() ||
7610 RightDeclRef->getLocation().isMacroID())
7611 return;
7612 const ValueDecl *LeftDecl =
7613 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7614 const ValueDecl *RightDecl =
7615 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7616 if (LeftDecl != RightDecl)
7617 return;
7618 if (LeftDecl->getType().isVolatileQualified())
7619 return;
7620 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7621 if (RefTy->getPointeeType().isVolatileQualified())
7622 return;
7623
7624 S.Diag(OpLoc, diag::warn_self_assignment)
7625 << LeftDeclRef->getType()
7626 << lhs->getSourceRange() << rhs->getSourceRange();
7627}
7628
Richard Trieue648ac32011-09-02 03:48:46 +00007629// checkArithmeticNull - Detect when a NULL constant is used improperly in an
7630// expression. These are mainly cases where the null pointer is used as an
7631// integer instead of a pointer.
7632static void checkArithmeticNull(Sema &S, ExprResult &lex, ExprResult &rex,
7633 SourceLocation Loc, bool isCompare) {
7634 // The canonical way to check for a GNU null is with isNullPointerConstant,
7635 // but we use a bit of a hack here for speed; this is a relatively
7636 // hot path, and isNullPointerConstant is slow.
7637 bool LeftNull = isa<GNUNullExpr>(lex.get()->IgnoreParenImpCasts());
7638 bool RightNull = isa<GNUNullExpr>(rex.get()->IgnoreParenImpCasts());
7639
7640 // Detect when a NULL constant is used improperly in an expression. These
7641 // are mainly cases where the null pointer is used as an integer instead
7642 // of a pointer.
7643 if (!LeftNull && !RightNull)
7644 return;
7645
7646 QualType LeftType = lex.get()->getType();
7647 QualType RightType = rex.get()->getType();
7648
7649 // Avoid analyzing cases where the result will either be invalid (and
7650 // diagnosed as such) or entirely valid and not something to warn about.
7651 if (LeftType->isBlockPointerType() || LeftType->isMemberPointerType() ||
7652 LeftType->isFunctionType() || RightType->isBlockPointerType() ||
7653 RightType->isMemberPointerType() || RightType->isFunctionType())
7654 return;
7655
7656 // Comparison operations would not make sense with a null pointer no matter
7657 // what the other expression is.
7658 if (!isCompare) {
7659 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
7660 << (LeftNull ? lex.get()->getSourceRange() : SourceRange())
7661 << (RightNull ? rex.get()->getSourceRange() : SourceRange());
7662 return;
7663 }
7664
7665 // The rest of the operations only make sense with a null pointer
7666 // if the other expression is a pointer.
7667 if (LeftNull == RightNull || LeftType->isAnyPointerType() ||
7668 LeftType->canDecayToPointerType() || RightType->isAnyPointerType() ||
7669 RightType->canDecayToPointerType())
7670 return;
7671
7672 S.Diag(Loc, diag::warn_null_in_comparison_operation)
7673 << LeftNull /* LHS is NULL */
7674 << (LeftNull ? rex.get()->getType() : lex.get()->getType())
7675 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
7676}
Douglas Gregoreaebc752008-11-06 23:29:22 +00007677/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7678/// operator @p Opc at location @c TokLoc. This routine only supports
7679/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00007680ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007681 BinaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007682 Expr *lhsExpr, Expr *rhsExpr) {
7683 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007684 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00007685 // The following two variables are used for compound assignment operators
7686 QualType CompLHSTy; // Type of LHS after promotions for computation
7687 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00007688 ExprValueKind VK = VK_RValue;
7689 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00007690
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007691 // Check if a 'foo<int>' involved in a binary op, identifies a single
7692 // function unambiguously (i.e. an lvalue ala 13.4)
7693 // But since an assignment can trigger target based overload, exclude it in
7694 // our blind search. i.e:
7695 // template<class T> void f(); template<class T, class U> void f(U);
7696 // f<int> == 0; // resolve f<int> blindly
7697 // void (*p)(int); p = f<int>; // resolve f<int> using target
7698 if (Opc != BO_Assign) {
John McCallfb8721c2011-04-10 19:13:55 +00007699 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007700 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00007701 lhs = move(resolvedLHS);
John McCall1de4d4e2011-04-07 08:22:57 +00007702
John McCallfb8721c2011-04-10 19:13:55 +00007703 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007704 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00007705 rhs = move(resolvedRHS);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007706 }
7707
Richard Trieue648ac32011-09-02 03:48:46 +00007708 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
7709 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
7710 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
7711 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
7712 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
7713 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign)
7714 checkArithmeticNull(*this, lhs, rhs, OpLoc, /*isCompare=*/false);
7715 else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
7716 Opc == BO_EQ || Opc == BO_NE)
7717 checkArithmeticNull(*this, lhs, rhs, OpLoc, /*isCompare=*/true);
Richard Trieu3e95ba92011-06-16 21:36:56 +00007718
Douglas Gregoreaebc752008-11-06 23:29:22 +00007719 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007720 case BO_Assign:
John Wiegley429bb272011-04-08 18:41:53 +00007721 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00007722 if (getLangOptions().CPlusPlus &&
John Wiegley429bb272011-04-08 18:41:53 +00007723 lhs.get()->getObjectKind() != OK_ObjCProperty) {
7724 VK = lhs.get()->getValueKind();
7725 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007726 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007727 if (!ResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00007728 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007729 break;
John McCall2de56d12010-08-25 11:45:40 +00007730 case BO_PtrMemD:
7731 case BO_PtrMemI:
John McCallf89e55a2010-11-18 06:31:45 +00007732 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007733 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00007734 break;
John McCall2de56d12010-08-25 11:45:40 +00007735 case BO_Mul:
7736 case BO_Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007737 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00007738 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007739 break;
John McCall2de56d12010-08-25 11:45:40 +00007740 case BO_Rem:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007741 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7742 break;
John McCall2de56d12010-08-25 11:45:40 +00007743 case BO_Add:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007744 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7745 break;
John McCall2de56d12010-08-25 11:45:40 +00007746 case BO_Sub:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007747 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7748 break;
John McCall2de56d12010-08-25 11:45:40 +00007749 case BO_Shl:
7750 case BO_Shr:
Chandler Carruth21206d52011-02-23 23:34:11 +00007751 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007752 break;
John McCall2de56d12010-08-25 11:45:40 +00007753 case BO_LE:
7754 case BO_LT:
7755 case BO_GE:
7756 case BO_GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00007757 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007758 break;
John McCall2de56d12010-08-25 11:45:40 +00007759 case BO_EQ:
7760 case BO_NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00007761 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007762 break;
John McCall2de56d12010-08-25 11:45:40 +00007763 case BO_And:
7764 case BO_Xor:
7765 case BO_Or:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007766 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7767 break;
John McCall2de56d12010-08-25 11:45:40 +00007768 case BO_LAnd:
7769 case BO_LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00007770 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007771 break;
John McCall2de56d12010-08-25 11:45:40 +00007772 case BO_MulAssign:
7773 case BO_DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007774 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00007775 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007776 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007777 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7778 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007779 break;
John McCall2de56d12010-08-25 11:45:40 +00007780 case BO_RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007781 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7782 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007783 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7784 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007785 break;
John McCall2de56d12010-08-25 11:45:40 +00007786 case BO_AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007787 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00007788 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7789 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007790 break;
John McCall2de56d12010-08-25 11:45:40 +00007791 case BO_SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007792 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00007793 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7794 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007795 break;
John McCall2de56d12010-08-25 11:45:40 +00007796 case BO_ShlAssign:
7797 case BO_ShrAssign:
Chandler Carruth21206d52011-02-23 23:34:11 +00007798 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007799 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007800 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7801 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007802 break;
John McCall2de56d12010-08-25 11:45:40 +00007803 case BO_AndAssign:
7804 case BO_XorAssign:
7805 case BO_OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007806 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7807 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007808 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7809 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007810 break;
John McCall2de56d12010-08-25 11:45:40 +00007811 case BO_Comma:
John McCall09431682010-11-18 19:01:18 +00007812 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00007813 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
7814 VK = rhs.get()->getValueKind();
7815 OK = rhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007816 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00007817 break;
7818 }
John Wiegley429bb272011-04-08 18:41:53 +00007819 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00007820 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007821
7822 // Check for array bounds violations for both sides of the BinaryOperator
7823 CheckArrayAccess(lhs.get());
7824 CheckArrayAccess(rhs.get());
7825
Eli Friedmanab3a8522009-03-28 01:22:36 +00007826 if (CompResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00007827 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
7828 ResultTy, VK, OK, OpLoc));
Richard Trieu67e29332011-08-02 04:35:43 +00007829 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() !=
7830 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00007831 VK = VK_LValue;
John Wiegley429bb272011-04-08 18:41:53 +00007832 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007833 }
John Wiegley429bb272011-04-08 18:41:53 +00007834 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
7835 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00007836 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00007837}
7838
Sebastian Redlaee3c932009-10-27 12:10:02 +00007839/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7840/// operators are mixed in a way that suggests that the programmer forgot that
7841/// comparison operators have higher precedence. The most typical example of
7842/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00007843static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007844 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00007845 typedef BinaryOperator BinOp;
7846 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7847 rhsopc = static_cast<BinOp::Opcode>(-1);
7848 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007849 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00007850 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007851 rhsopc = BO->getOpcode();
7852
7853 // Subs are not binary operators.
7854 if (lhsopc == -1 && rhsopc == -1)
7855 return;
7856
7857 // Bitwise operations are sometimes used as eager logical ops.
7858 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00007859 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7860 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007861 return;
7862
Richard Trieu70979d42011-08-10 22:41:34 +00007863 bool isLeftComp = BinOp::isComparisonOp(lhsopc);
7864 bool isRightComp = BinOp::isComparisonOp(rhsopc);
7865 if (!isLeftComp && !isRightComp) return;
7866
7867 SourceRange DiagRange = isLeftComp ? SourceRange(lhs->getLocStart(), OpLoc)
7868 : SourceRange(OpLoc, rhs->getLocEnd());
7869 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(lhsopc)
7870 : BinOp::getOpcodeStr(rhsopc);
7871 SourceRange ParensRange = isLeftComp ?
7872 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(),
7873 rhs->getLocEnd())
7874 : SourceRange(lhs->getLocStart(),
7875 cast<BinOp>(rhs)->getLHS()->getLocStart());
7876
7877 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7878 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7879 SuggestParentheses(Self, OpLoc,
7880 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
7881 rhs->getSourceRange());
7882 SuggestParentheses(Self, OpLoc,
7883 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7884 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007885}
7886
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007887/// \brief It accepts a '&' expr that is inside a '|' one.
7888/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7889/// in parentheses.
7890static void
7891EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7892 BinaryOperator *Bop) {
7893 assert(Bop->getOpcode() == BO_And);
7894 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7895 << Bop->getSourceRange() << OpLoc;
7896 SuggestParentheses(Self, Bop->getOperatorLoc(),
7897 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7898 Bop->getSourceRange());
7899}
7900
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007901/// \brief It accepts a '&&' expr that is inside a '||' one.
7902/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7903/// in parentheses.
7904static void
7905EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00007906 BinaryOperator *Bop) {
7907 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007908 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7909 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00007910 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007911 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007912 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007913}
7914
7915/// \brief Returns true if the given expression can be evaluated as a constant
7916/// 'true'.
7917static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7918 bool Res;
7919 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7920}
7921
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007922/// \brief Returns true if the given expression can be evaluated as a constant
7923/// 'false'.
7924static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7925 bool Res;
7926 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7927}
7928
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007929/// \brief Look for '&&' in the left hand of a '||' expr.
7930static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007931 Expr *OrLHS, Expr *OrRHS) {
7932 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007933 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007934 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7935 if (EvaluatesAsFalse(S, OrRHS))
7936 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007937 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7938 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7939 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7940 } else if (Bop->getOpcode() == BO_LOr) {
7941 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7942 // If it's "a || b && 1 || c" we didn't warn earlier for
7943 // "a || b && 1", but warn now.
7944 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7945 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7946 }
7947 }
7948 }
7949}
7950
7951/// \brief Look for '&&' in the right hand of a '||' expr.
7952static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007953 Expr *OrLHS, Expr *OrRHS) {
7954 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007955 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007956 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7957 if (EvaluatesAsFalse(S, OrLHS))
7958 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007959 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7960 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7961 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007962 }
7963 }
7964}
7965
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007966/// \brief Look for '&' in the left or right hand of a '|' expr.
7967static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7968 Expr *OrArg) {
7969 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7970 if (Bop->getOpcode() == BO_And)
7971 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7972 }
7973}
7974
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007975/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007976/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00007977static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007978 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007979 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00007980 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007981 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7982
7983 // Diagnose "arg1 & arg2 | arg3"
7984 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7985 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, lhs);
7986 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, rhs);
7987 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007988
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007989 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7990 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00007991 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007992 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7993 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007994 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007995}
7996
Reid Spencer5f016e22007-07-11 17:01:13 +00007997// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00007998ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00007999 tok::TokenKind Kind,
8000 Expr *lhs, Expr *rhs) {
8001 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Narofff69936d2007-09-16 03:34:24 +00008002 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8003 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008004
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008005 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8006 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8007
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008008 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8009}
8010
John McCall60d7b3a2010-08-24 06:29:42 +00008011ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008012 BinaryOperatorKind Opc,
8013 Expr *lhs, Expr *rhs) {
John McCall01b2e4e2010-12-06 05:26:58 +00008014 if (getLangOptions().CPlusPlus) {
8015 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008016
John McCall01b2e4e2010-12-06 05:26:58 +00008017 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8018 UseBuiltinOperator = false;
8019 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8020 UseBuiltinOperator = true;
8021 } else {
8022 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8023 !rhs->getType()->isOverloadableType();
8024 }
8025
8026 if (!UseBuiltinOperator) {
8027 // Find all of the overloaded operators visible from this
8028 // point. We perform both an operator-name lookup from the local
8029 // scope and an argument-dependent lookup based on the types of
8030 // the arguments.
8031 UnresolvedSet<16> Functions;
8032 OverloadedOperatorKind OverOp
8033 = BinaryOperator::getOverloadedOperator(Opc);
8034 if (S && OverOp != OO_None)
8035 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8036 Functions);
8037
8038 // Build the (potentially-overloaded, potentially-dependent)
8039 // binary operation.
8040 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8041 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008042 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008043
Douglas Gregoreaebc752008-11-06 23:29:22 +00008044 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008045 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00008046}
8047
John McCall60d7b3a2010-08-24 06:29:42 +00008048ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008049 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008050 Expr *InputExpr) {
8051 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008052 ExprValueKind VK = VK_RValue;
8053 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008054 QualType resultType;
8055 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008056 case UO_PreInc:
8057 case UO_PreDec:
8058 case UO_PostInc:
8059 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008060 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008061 Opc == UO_PreInc ||
8062 Opc == UO_PostInc,
8063 Opc == UO_PreInc ||
8064 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008065 break;
John McCall2de56d12010-08-25 11:45:40 +00008066 case UO_AddrOf:
John Wiegley429bb272011-04-08 18:41:53 +00008067 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008068 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008069 case UO_Deref: {
John McCallfb8721c2011-04-10 19:13:55 +00008070 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008071 if (!resolved.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008072 Input = move(resolved);
8073 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8074 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008075 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008076 }
John McCall2de56d12010-08-25 11:45:40 +00008077 case UO_Plus:
8078 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008079 Input = UsualUnaryConversions(Input.take());
8080 if (Input.isInvalid()) return ExprError();
8081 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008082 if (resultType->isDependentType())
8083 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008084 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8085 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008086 break;
8087 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8088 resultType->isEnumeralType())
8089 break;
8090 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008091 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008092 resultType->isPointerType())
8093 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008094 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008095 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008096 if (Input.isInvalid()) return ExprError();
8097 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008098 }
Douglas Gregor74253732008-11-19 15:42:04 +00008099
Sebastian Redl0eb23302009-01-19 00:08:26 +00008100 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008101 << resultType << Input.get()->getSourceRange());
8102
John McCall2de56d12010-08-25 11:45:40 +00008103 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008104 Input = UsualUnaryConversions(Input.take());
8105 if (Input.isInvalid()) return ExprError();
8106 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008107 if (resultType->isDependentType())
8108 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008109 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8110 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8111 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008112 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008113 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008114 else if (resultType->hasIntegerRepresentation())
8115 break;
8116 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008117 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008118 if (Input.isInvalid()) return ExprError();
8119 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008120 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008121 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008122 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008123 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008124 break;
John Wiegley429bb272011-04-08 18:41:53 +00008125
John McCall2de56d12010-08-25 11:45:40 +00008126 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008127 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008128 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8129 if (Input.isInvalid()) return ExprError();
8130 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008131 if (resultType->isDependentType())
8132 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008133 if (resultType->isScalarType()) {
8134 // C99 6.5.3.3p1: ok, fallthrough;
8135 if (Context.getLangOptions().CPlusPlus) {
8136 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8137 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008138 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8139 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008140 }
John McCall2cd11fe2010-10-12 02:09:17 +00008141 } else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008142 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008143 if (Input.isInvalid()) return ExprError();
8144 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008145 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008146 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008147 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008148 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008149
Reid Spencer5f016e22007-07-11 17:01:13 +00008150 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008151 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008152 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008153 break;
John McCall2de56d12010-08-25 11:45:40 +00008154 case UO_Real:
8155 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008156 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00008157 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley429bb272011-04-08 18:41:53 +00008158 if (Input.isInvalid()) return ExprError();
8159 if (Input.get()->getValueKind() != VK_RValue &&
8160 Input.get()->getObjectKind() == OK_Ordinary)
8161 VK = Input.get()->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00008162 break;
John McCall2de56d12010-08-25 11:45:40 +00008163 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008164 resultType = Input.get()->getType();
8165 VK = Input.get()->getValueKind();
8166 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008167 break;
8168 }
John Wiegley429bb272011-04-08 18:41:53 +00008169 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008170 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008171
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008172 // Check for array bounds violations in the operand of the UnaryOperator,
8173 // except for the '*' and '&' operators that have to be handled specially
8174 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8175 // that are explicitly defined as valid by the standard).
8176 if (Opc != UO_AddrOf && Opc != UO_Deref)
8177 CheckArrayAccess(Input.get());
8178
John Wiegley429bb272011-04-08 18:41:53 +00008179 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008180 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008181}
8182
John McCall60d7b3a2010-08-24 06:29:42 +00008183ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008184 UnaryOperatorKind Opc,
8185 Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00008186 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00008187 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008188 // Find all of the overloaded operators visible from this
8189 // point. We perform both an operator-name lookup from the local
8190 // scope and an argument-dependent lookup based on the types of
8191 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008192 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008193 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008194 if (S && OverOp != OO_None)
8195 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8196 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008197
John McCall9ae2f072010-08-23 23:25:46 +00008198 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008199 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008200
John McCall9ae2f072010-08-23 23:25:46 +00008201 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008202}
8203
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008204// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008205ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008206 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008207 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008208}
8209
Steve Naroff1b273c42007-09-16 14:56:35 +00008210/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008211ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008212 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008213 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008214 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008215 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008216 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008217}
8218
John McCallf85e1932011-06-15 23:02:42 +00008219/// Given the last statement in a statement-expression, check whether
8220/// the result is a producing expression (like a call to an
8221/// ns_returns_retained function) and, if so, rebuild it to hoist the
8222/// release out of the full-expression. Otherwise, return null.
8223/// Cannot fail.
8224static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
8225 // Should always be wrapped with one of these.
8226 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
8227 if (!cleanups) return 0;
8228
8229 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
8230 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
8231 return 0;
8232
8233 // Splice out the cast. This shouldn't modify any interesting
8234 // features of the statement.
8235 Expr *producer = cast->getSubExpr();
8236 assert(producer->getType() == cast->getType());
8237 assert(producer->getValueKind() == cast->getValueKind());
8238 cleanups->setSubExpr(producer);
8239 return cleanups;
8240}
8241
John McCall60d7b3a2010-08-24 06:29:42 +00008242ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008243Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008244 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008245 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8246 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8247
Douglas Gregordd8f5692010-03-10 04:54:39 +00008248 bool isFileScope
8249 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008250 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008251 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008252
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008253 // FIXME: there are a variety of strange constraints to enforce here, for
8254 // example, it is not possible to goto into a stmt expression apparently.
8255 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008256
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008257 // If there are sub stmts in the compound stmt, take the type of the last one
8258 // as the type of the stmtexpr.
8259 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008260 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008261 if (!Compound->body_empty()) {
8262 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008263 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008264 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008265 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8266 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008267 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008268 }
John McCallf85e1932011-06-15 23:02:42 +00008269
John Wiegley429bb272011-04-08 18:41:53 +00008270 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008271 // Do function/array conversion on the last expression, but not
8272 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00008273 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8274 if (LastExpr.isInvalid())
8275 return ExprError();
8276 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00008277
John Wiegley429bb272011-04-08 18:41:53 +00008278 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00008279 // In ARC, if the final expression ends in a consume, splice
8280 // the consume out and bind it later. In the alternate case
8281 // (when dealing with a retainable type), the result
8282 // initialization will create a produce. In both cases the
8283 // result will be +1, and we'll need to balance that out with
8284 // a bind.
8285 if (Expr *rebuiltLastStmt
8286 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8287 LastExpr = rebuiltLastStmt;
8288 } else {
8289 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008290 InitializedEntity::InitializeResult(LPLoc,
8291 Ty,
8292 false),
8293 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00008294 LastExpr);
8295 }
8296
John Wiegley429bb272011-04-08 18:41:53 +00008297 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008298 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008299 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008300 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00008301 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008302 else
John Wiegley429bb272011-04-08 18:41:53 +00008303 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008304 StmtExprMayBindToTemp = true;
8305 }
8306 }
8307 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008308 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008309
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008310 // FIXME: Check that expression type is complete/non-abstract; statement
8311 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008312 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8313 if (StmtExprMayBindToTemp)
8314 return MaybeBindToTemporary(ResStmtExpr);
8315 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008316}
Steve Naroffd34e9152007-08-01 22:05:33 +00008317
John McCall60d7b3a2010-08-24 06:29:42 +00008318ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008319 TypeSourceInfo *TInfo,
8320 OffsetOfComponent *CompPtr,
8321 unsigned NumComponents,
8322 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008323 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008324 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008325 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008326
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008327 // We must have at least one component that refers to the type, and the first
8328 // one is known to be a field designator. Verify that the ArgTy represents
8329 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008330 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008331 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8332 << ArgTy << TypeRange);
8333
8334 // Type must be complete per C99 7.17p3 because a declaring a variable
8335 // with an incomplete type would be ill-formed.
8336 if (!Dependent
8337 && RequireCompleteType(BuiltinLoc, ArgTy,
8338 PDiag(diag::err_offsetof_incomplete_type)
8339 << TypeRange))
8340 return ExprError();
8341
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008342 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8343 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00008344 // FIXME: This diagnostic isn't actually visible because the location is in
8345 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008346 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008347 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8348 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008349
8350 bool DidWarnAboutNonPOD = false;
8351 QualType CurrentType = ArgTy;
8352 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008353 SmallVector<OffsetOfNode, 4> Comps;
8354 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008355 for (unsigned i = 0; i != NumComponents; ++i) {
8356 const OffsetOfComponent &OC = CompPtr[i];
8357 if (OC.isBrackets) {
8358 // Offset of an array sub-field. TODO: Should we allow vector elements?
8359 if (!CurrentType->isDependentType()) {
8360 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8361 if(!AT)
8362 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8363 << CurrentType);
8364 CurrentType = AT->getElementType();
8365 } else
8366 CurrentType = Context.DependentTy;
8367
8368 // The expression must be an integral expression.
8369 // FIXME: An integral constant expression?
8370 Expr *Idx = static_cast<Expr*>(OC.U.E);
8371 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8372 !Idx->getType()->isIntegerType())
8373 return ExprError(Diag(Idx->getLocStart(),
8374 diag::err_typecheck_subscript_not_integer)
8375 << Idx->getSourceRange());
8376
8377 // Record this array index.
8378 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8379 Exprs.push_back(Idx);
8380 continue;
8381 }
8382
8383 // Offset of a field.
8384 if (CurrentType->isDependentType()) {
8385 // We have the offset of a field, but we can't look into the dependent
8386 // type. Just record the identifier of the field.
8387 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8388 CurrentType = Context.DependentTy;
8389 continue;
8390 }
8391
8392 // We need to have a complete type to look into.
8393 if (RequireCompleteType(OC.LocStart, CurrentType,
8394 diag::err_offsetof_incomplete_type))
8395 return ExprError();
8396
8397 // Look for the designated field.
8398 const RecordType *RC = CurrentType->getAs<RecordType>();
8399 if (!RC)
8400 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8401 << CurrentType);
8402 RecordDecl *RD = RC->getDecl();
8403
8404 // C++ [lib.support.types]p5:
8405 // The macro offsetof accepts a restricted set of type arguments in this
8406 // International Standard. type shall be a POD structure or a POD union
8407 // (clause 9).
8408 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8409 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00008410 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008411 PDiag(diag::warn_offsetof_non_pod_type)
8412 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8413 << CurrentType))
8414 DidWarnAboutNonPOD = true;
8415 }
8416
8417 // Look for the field.
8418 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8419 LookupQualifiedName(R, RD);
8420 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00008421 IndirectFieldDecl *IndirectMemberDecl = 0;
8422 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00008423 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00008424 MemberDecl = IndirectMemberDecl->getAnonField();
8425 }
8426
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008427 if (!MemberDecl)
8428 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8429 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8430 OC.LocEnd));
8431
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00008432 // C99 7.17p3:
8433 // (If the specified member is a bit-field, the behavior is undefined.)
8434 //
8435 // We diagnose this as an error.
8436 if (MemberDecl->getBitWidth()) {
8437 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8438 << MemberDecl->getDeclName()
8439 << SourceRange(BuiltinLoc, RParenLoc);
8440 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8441 return ExprError();
8442 }
Eli Friedman19410a72010-08-05 10:11:36 +00008443
8444 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00008445 if (IndirectMemberDecl)
8446 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00008447
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008448 // If the member was found in a base class, introduce OffsetOfNodes for
8449 // the base class indirections.
8450 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8451 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00008452 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008453 CXXBasePath &Path = Paths.front();
8454 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8455 B != BEnd; ++B)
8456 Comps.push_back(OffsetOfNode(B->Base));
8457 }
Eli Friedman19410a72010-08-05 10:11:36 +00008458
Francois Pichet87c2e122010-11-21 06:08:52 +00008459 if (IndirectMemberDecl) {
8460 for (IndirectFieldDecl::chain_iterator FI =
8461 IndirectMemberDecl->chain_begin(),
8462 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8463 assert(isa<FieldDecl>(*FI));
8464 Comps.push_back(OffsetOfNode(OC.LocStart,
8465 cast<FieldDecl>(*FI), OC.LocEnd));
8466 }
8467 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008468 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00008469
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008470 CurrentType = MemberDecl->getType().getNonReferenceType();
8471 }
8472
8473 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8474 TInfo, Comps.data(), Comps.size(),
8475 Exprs.data(), Exprs.size(), RParenLoc));
8476}
Mike Stumpeed9cac2009-02-19 03:04:26 +00008477
John McCall60d7b3a2010-08-24 06:29:42 +00008478ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00008479 SourceLocation BuiltinLoc,
8480 SourceLocation TypeLoc,
8481 ParsedType argty,
8482 OffsetOfComponent *CompPtr,
8483 unsigned NumComponents,
8484 SourceLocation RPLoc) {
8485
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008486 TypeSourceInfo *ArgTInfo;
8487 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8488 if (ArgTy.isNull())
8489 return ExprError();
8490
Eli Friedman5a15dc12010-08-05 10:15:45 +00008491 if (!ArgTInfo)
8492 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8493
8494 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8495 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008496}
8497
8498
John McCall60d7b3a2010-08-24 06:29:42 +00008499ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008500 Expr *CondExpr,
8501 Expr *LHSExpr, Expr *RHSExpr,
8502 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00008503 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8504
John McCallf89e55a2010-11-18 06:31:45 +00008505 ExprValueKind VK = VK_RValue;
8506 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00008507 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00008508 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00008509 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00008510 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00008511 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00008512 } else {
8513 // The conditional expression is required to be a constant expression.
8514 llvm::APSInt condEval(32);
8515 SourceLocation ExpLoc;
8516 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00008517 return ExprError(Diag(ExpLoc,
8518 diag::err_typecheck_choose_expr_requires_constant)
8519 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00008520
Sebastian Redl28507842009-02-26 14:39:58 +00008521 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00008522 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8523
8524 resType = ActiveExpr->getType();
8525 ValueDependent = ActiveExpr->isValueDependent();
8526 VK = ActiveExpr->getValueKind();
8527 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00008528 }
8529
Sebastian Redlf53597f2009-03-15 17:47:39 +00008530 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008531 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00008532 resType->isDependentType(),
8533 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00008534}
8535
Steve Naroff4eb206b2008-09-03 18:15:37 +00008536//===----------------------------------------------------------------------===//
8537// Clang Extensions.
8538//===----------------------------------------------------------------------===//
8539
8540/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00008541void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008542 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8543 PushBlockScope(BlockScope, Block);
8544 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008545 if (BlockScope)
8546 PushDeclContext(BlockScope, Block);
8547 else
8548 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00008549}
8550
Mike Stump98eb8a72009-02-04 22:31:32 +00008551void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00008552 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00008553 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008554 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008555
John McCallbf1a0282010-06-04 23:28:52 +00008556 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00008557 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00008558
John McCall711c52b2011-01-05 12:14:39 +00008559 // GetTypeForDeclarator always produces a function type for a block
8560 // literal signature. Furthermore, it is always a FunctionProtoType
8561 // unless the function was written with a typedef.
8562 assert(T->isFunctionType() &&
8563 "GetTypeForDeclarator made a non-function block signature");
8564
8565 // Look for an explicit signature in that function type.
8566 FunctionProtoTypeLoc ExplicitSignature;
8567
8568 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8569 if (isa<FunctionProtoTypeLoc>(tmp)) {
8570 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8571
8572 // Check whether that explicit signature was synthesized by
8573 // GetTypeForDeclarator. If so, don't save that as part of the
8574 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00008575 if (ExplicitSignature.getLocalRangeBegin() ==
8576 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00008577 // This would be much cheaper if we stored TypeLocs instead of
8578 // TypeSourceInfos.
8579 TypeLoc Result = ExplicitSignature.getResultLoc();
8580 unsigned Size = Result.getFullDataSize();
8581 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8582 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8583
8584 ExplicitSignature = FunctionProtoTypeLoc();
8585 }
John McCall82dc0092010-06-04 11:21:44 +00008586 }
Mike Stump1eb44332009-09-09 15:08:12 +00008587
John McCall711c52b2011-01-05 12:14:39 +00008588 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8589 CurBlock->FunctionType = T;
8590
8591 const FunctionType *Fn = T->getAs<FunctionType>();
8592 QualType RetTy = Fn->getResultType();
8593 bool isVariadic =
8594 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8595
John McCallc71a4912010-06-04 19:02:56 +00008596 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00008597
John McCall82dc0092010-06-04 11:21:44 +00008598 // Don't allow returning a objc interface by value.
8599 if (RetTy->isObjCObjectType()) {
8600 Diag(ParamInfo.getSourceRange().getBegin(),
8601 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8602 return;
8603 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008604
John McCall82dc0092010-06-04 11:21:44 +00008605 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00008606 // return type. TODO: what should we do with declarators like:
8607 // ^ * { ... }
8608 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00008609 if (RetTy != Context.DependentTy)
8610 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008611
John McCall82dc0092010-06-04 11:21:44 +00008612 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008613 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00008614 if (ExplicitSignature) {
8615 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8616 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008617 if (Param->getIdentifier() == 0 &&
8618 !Param->isImplicit() &&
8619 !Param->isInvalidDecl() &&
8620 !getLangOptions().CPlusPlus)
8621 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00008622 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008623 }
John McCall82dc0092010-06-04 11:21:44 +00008624
8625 // Fake up parameter variables if we have a typedef, like
8626 // ^ fntype { ... }
8627 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8628 for (FunctionProtoType::arg_type_iterator
8629 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8630 ParmVarDecl *Param =
8631 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8632 ParamInfo.getSourceRange().getBegin(),
8633 *I);
John McCallc71a4912010-06-04 19:02:56 +00008634 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00008635 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008636 }
John McCall82dc0092010-06-04 11:21:44 +00008637
John McCallc71a4912010-06-04 19:02:56 +00008638 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00008639 if (!Params.empty()) {
John McCallc71a4912010-06-04 19:02:56 +00008640 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregor82aa7132010-11-01 18:37:59 +00008641 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8642 CurBlock->TheDecl->param_end(),
8643 /*CheckParameterNames=*/false);
8644 }
8645
John McCall82dc0092010-06-04 11:21:44 +00008646 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008647 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00008648
John McCallc71a4912010-06-04 19:02:56 +00008649 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00008650 Diag(ParamInfo.getAttributes()->getLoc(),
8651 diag::warn_attribute_sentinel_not_variadic) << 1;
8652 // FIXME: remove the attribute.
8653 }
8654
8655 // Put the parameter variables in scope. We can bail out immediately
8656 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00008657 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00008658 return;
8659
Steve Naroff090276f2008-10-10 01:28:17 +00008660 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00008661 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8662 (*AI)->setOwningFunction(CurBlock->TheDecl);
8663
Steve Naroff090276f2008-10-10 01:28:17 +00008664 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00008665 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008666 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00008667
Steve Naroff090276f2008-10-10 01:28:17 +00008668 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00008669 }
John McCall7a9813c2010-01-22 00:28:27 +00008670 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008671}
8672
8673/// ActOnBlockError - If there is an error parsing a block, this callback
8674/// is invoked to pop the information about the block from the action impl.
8675void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00008676 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00008677 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008678 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008679}
8680
8681/// ActOnBlockStmtExpr - This is called when the body of a block statement
8682/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00008683ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00008684 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00008685 // If blocks are disabled, emit an error.
8686 if (!LangOpts.Blocks)
8687 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00008688
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008689 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008690
Steve Naroff090276f2008-10-10 01:28:17 +00008691 PopDeclContext();
8692
Steve Naroff4eb206b2008-09-03 18:15:37 +00008693 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00008694 if (!BSI->ReturnType.isNull())
8695 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008696
Mike Stump56925862009-07-28 22:04:01 +00008697 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008698 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00008699
John McCall469a1eb2011-02-02 13:00:07 +00008700 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00008701 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8702 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00008703
John McCallc71a4912010-06-04 19:02:56 +00008704 // If the user wrote a function type in some form, try to use that.
8705 if (!BSI->FunctionType.isNull()) {
8706 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8707
8708 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8709 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8710
8711 // Turn protoless block types into nullary block types.
8712 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00008713 FunctionProtoType::ExtProtoInfo EPI;
8714 EPI.ExtInfo = Ext;
8715 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008716
8717 // Otherwise, if we don't need to change anything about the function type,
8718 // preserve its sugar structure.
8719 } else if (FTy->getResultType() == RetTy &&
8720 (!NoReturn || FTy->getNoReturnAttr())) {
8721 BlockTy = BSI->FunctionType;
8722
8723 // Otherwise, make the minimal modifications to the function type.
8724 } else {
8725 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00008726 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8727 EPI.TypeQuals = 0; // FIXME: silently?
8728 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00008729 BlockTy = Context.getFunctionType(RetTy,
8730 FPT->arg_type_begin(),
8731 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00008732 EPI);
John McCallc71a4912010-06-04 19:02:56 +00008733 }
8734
8735 // If we don't have a function type, just build one from nothing.
8736 } else {
John McCalle23cf432010-12-14 08:05:40 +00008737 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00008738 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00008739 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008740 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008741
John McCallc71a4912010-06-04 19:02:56 +00008742 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8743 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00008744 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008745
Chris Lattner17a78302009-04-19 05:28:12 +00008746 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00008747 if (getCurFunction()->NeedsScopeChecking() &&
8748 !hasAnyUnrecoverableErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00008749 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00008750
Chris Lattnere476bdc2011-02-17 23:58:47 +00008751 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008752
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +00008753 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8754 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8755 const VarDecl *variable = ci->getVariable();
8756 QualType T = variable->getType();
8757 QualType::DestructionKind destructKind = T.isDestructedType();
8758 if (destructKind != QualType::DK_none)
8759 getCurFunction()->setHasBranchProtectedScope();
8760 }
8761
Benjamin Kramerd2486192011-07-12 14:11:05 +00008762 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8763 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8764 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8765
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008766 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00008767}
8768
John McCall60d7b3a2010-08-24 06:29:42 +00008769ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallb3d87482010-08-24 05:47:05 +00008770 Expr *expr, ParsedType type,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008771 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008772 TypeSourceInfo *TInfo;
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008773 GetTypeFromParser(type, &TInfo);
John McCall9ae2f072010-08-23 23:25:46 +00008774 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008775}
8776
John McCall60d7b3a2010-08-24 06:29:42 +00008777ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00008778 Expr *E, TypeSourceInfo *TInfo,
8779 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008780 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00008781
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008782 // Get the va_list type
8783 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008784 if (VaListType->isArrayType()) {
8785 // Deal with implicit array decay; for example, on x86-64,
8786 // va_list is an array, but it's supposed to decay to
8787 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008788 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00008789 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00008790 ExprResult Result = UsualUnaryConversions(E);
8791 if (Result.isInvalid())
8792 return ExprError();
8793 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008794 } else {
8795 // Otherwise, the va_list argument must be an l-value because
8796 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00008797 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00008798 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00008799 return ExprError();
8800 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008801
Douglas Gregordd027302009-05-19 23:10:31 +00008802 if (!E->isTypeDependent() &&
8803 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00008804 return ExprError(Diag(E->getLocStart(),
8805 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008806 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00008807 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008808
David Majnemer0adde122011-06-14 05:17:32 +00008809 if (!TInfo->getType()->isDependentType()) {
8810 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8811 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8812 << TInfo->getTypeLoc().getSourceRange()))
8813 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00008814
David Majnemer0adde122011-06-14 05:17:32 +00008815 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8816 TInfo->getType(),
8817 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8818 << TInfo->getTypeLoc().getSourceRange()))
8819 return ExprError();
8820
Douglas Gregor4eb75222011-07-30 06:45:27 +00008821 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00008822 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00008823 TInfo->getType()->isObjCLifetimeType()
8824 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8825 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00008826 << TInfo->getType()
8827 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00008828 }
Eli Friedman46d37c12011-07-11 21:45:59 +00008829
8830 // Check for va_arg where arguments of the given type will be promoted
8831 // (i.e. this va_arg is guaranteed to have undefined behavior).
8832 QualType PromoteType;
8833 if (TInfo->getType()->isPromotableIntegerType()) {
8834 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8835 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8836 PromoteType = QualType();
8837 }
8838 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8839 PromoteType = Context.DoubleTy;
8840 if (!PromoteType.isNull())
8841 Diag(TInfo->getTypeLoc().getBeginLoc(),
8842 diag::warn_second_parameter_to_va_arg_never_compatible)
8843 << TInfo->getType()
8844 << PromoteType
8845 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00008846 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008847
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008848 QualType T = TInfo->getType().getNonLValueExprType(Context);
8849 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008850}
8851
John McCall60d7b3a2010-08-24 06:29:42 +00008852ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008853 // The type of __null will be int or long, depending on the size of
8854 // pointers on the target.
8855 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00008856 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
8857 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008858 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00008859 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008860 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00008861 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008862 Ty = Context.LongLongTy;
8863 else {
8864 assert(!"I don't know size of pointer!");
8865 Ty = Context.IntTy;
8866 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008867
Sebastian Redlf53597f2009-03-15 17:47:39 +00008868 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008869}
8870
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008871static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00008872 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008873 if (!SemaRef.getLangOptions().ObjC1)
8874 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008875
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008876 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8877 if (!PT)
8878 return;
8879
8880 // Check if the destination is of type 'id'.
8881 if (!PT->isObjCIdType()) {
8882 // Check if the destination is the 'NSString' interface.
8883 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8884 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8885 return;
8886 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008887
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008888 // Strip off any parens and casts.
8889 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregor5cee1192011-07-27 05:40:30 +00008890 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008891 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008892
Douglas Gregor849b2432010-03-31 17:46:05 +00008893 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008894}
8895
Chris Lattner5cf216b2008-01-04 18:04:52 +00008896bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8897 SourceLocation Loc,
8898 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00008899 Expr *SrcExpr, AssignmentAction Action,
8900 bool *Complained) {
8901 if (Complained)
8902 *Complained = false;
8903
Chris Lattner5cf216b2008-01-04 18:04:52 +00008904 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00008905 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008906 bool isInvalid = false;
8907 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00008908 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00008909 ConversionFixItGenerator ConvHints;
8910 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008911
Chris Lattner5cf216b2008-01-04 18:04:52 +00008912 switch (ConvTy) {
8913 default: assert(0 && "Unknown conversion type");
8914 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008915 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00008916 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00008917 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8918 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008919 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008920 case IntToPointer:
8921 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00008922 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8923 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008924 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008925 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00008926 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00008927 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00008928 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8929 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00008930 if (Hint.isNull() && !CheckInferredResultType) {
8931 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8932 }
8933 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008934 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00008935 case IncompatiblePointerSign:
8936 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8937 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008938 case FunctionVoidPointer:
8939 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8940 break;
John McCall86c05f32011-02-01 00:10:29 +00008941 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00008942 // Perform array-to-pointer decay if necessary.
8943 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8944
John McCall86c05f32011-02-01 00:10:29 +00008945 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8946 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8947 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8948 DiagKind = diag::err_typecheck_incompatible_address_space;
8949 break;
John McCallf85e1932011-06-15 23:02:42 +00008950
8951
8952 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008953 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00008954 break;
John McCall86c05f32011-02-01 00:10:29 +00008955 }
8956
8957 llvm_unreachable("unknown error case for discarding qualifiers!");
8958 // fallthrough
8959 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00008960 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00008961 // If the qualifiers lost were because we were applying the
8962 // (deprecated) C++ conversion from a string literal to a char*
8963 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8964 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00008965 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00008966 // bit of refactoring (so that the second argument is an
8967 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00008968 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00008969 // C++ semantics.
8970 if (getLangOptions().CPlusPlus &&
8971 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8972 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008973 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8974 break;
Sean Huntc9132b62009-11-08 07:46:34 +00008975 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00008976 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00008977 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00008978 case IntToBlockPointer:
8979 DiagKind = diag::err_int_to_block_pointer;
8980 break;
8981 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00008982 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00008983 break;
Steve Naroff39579072008-10-14 22:18:38 +00008984 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00008985 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00008986 // it can give a more specific diagnostic.
8987 DiagKind = diag::warn_incompatible_qualified_id;
8988 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00008989 case IncompatibleVectors:
8990 DiagKind = diag::warn_incompatible_vectors;
8991 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00008992 case IncompatibleObjCWeakRef:
8993 DiagKind = diag::err_arc_weak_unavailable_assign;
8994 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008995 case Incompatible:
8996 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00008997 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8998 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008999 isInvalid = true;
9000 break;
9001 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009002
Douglas Gregord4eea832010-04-09 00:35:39 +00009003 QualType FirstType, SecondType;
9004 switch (Action) {
9005 case AA_Assigning:
9006 case AA_Initializing:
9007 // The destination type comes first.
9008 FirstType = DstType;
9009 SecondType = SrcType;
9010 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009011
Douglas Gregord4eea832010-04-09 00:35:39 +00009012 case AA_Returning:
9013 case AA_Passing:
9014 case AA_Converting:
9015 case AA_Sending:
9016 case AA_Casting:
9017 // The source type comes first.
9018 FirstType = SrcType;
9019 SecondType = DstType;
9020 break;
9021 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009022
Anna Zaks67221552011-07-28 19:51:27 +00009023 PartialDiagnostic FDiag = PDiag(DiagKind);
9024 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9025
9026 // If we can fix the conversion, suggest the FixIts.
9027 assert(ConvHints.isNull() || Hint.isNull());
9028 if (!ConvHints.isNull()) {
9029 for (llvm::SmallVector<FixItHint, 1>::iterator
9030 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
9031 HI != HE; ++HI)
9032 FDiag << *HI;
9033 } else {
9034 FDiag << Hint;
9035 }
9036 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9037
9038 Diag(Loc, FDiag);
9039
Douglas Gregor926df6c2011-06-11 01:09:30 +00009040 if (CheckInferredResultType)
9041 EmitRelatedResultTypeNote(SrcExpr);
9042
Douglas Gregora41a8c52010-04-22 00:20:18 +00009043 if (Complained)
9044 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009045 return isInvalid;
9046}
Anders Carlssone21555e2008-11-30 19:50:32 +00009047
Chris Lattner3bf68932009-04-25 21:59:05 +00009048bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009049 llvm::APSInt ICEResult;
9050 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9051 if (Result)
9052 *Result = ICEResult;
9053 return false;
9054 }
9055
Anders Carlssone21555e2008-11-30 19:50:32 +00009056 Expr::EvalResult EvalResult;
9057
Mike Stumpeed9cac2009-02-19 03:04:26 +00009058 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00009059 EvalResult.HasSideEffects) {
9060 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9061
9062 if (EvalResult.Diag) {
9063 // We only show the note if it's not the usual "invalid subexpression"
9064 // or if it's actually in a subexpression.
9065 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9066 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9067 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9068 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009069
Anders Carlssone21555e2008-11-30 19:50:32 +00009070 return true;
9071 }
9072
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009073 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9074 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00009075
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009076 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009077 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9078 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009079 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009080
Anders Carlssone21555e2008-11-30 19:50:32 +00009081 if (Result)
9082 *Result = EvalResult.Val.getInt();
9083 return false;
9084}
Douglas Gregore0762c92009-06-19 23:52:42 +00009085
Douglas Gregor2afce722009-11-26 00:44:06 +00009086void
Mike Stump1eb44332009-09-09 15:08:12 +00009087Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009088 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +00009089 ExpressionEvaluationContextRecord(NewContext,
9090 ExprTemporaries.size(),
9091 ExprNeedsCleanups));
9092 ExprNeedsCleanups = false;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009093}
9094
Richard Trieu67e29332011-08-02 04:35:43 +00009095void Sema::PopExpressionEvaluationContext() {
Douglas Gregor2afce722009-11-26 00:44:06 +00009096 // Pop the current expression evaluation context off the stack.
9097 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9098 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009099
Douglas Gregor06d33692009-12-12 07:57:52 +00009100 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9101 if (Rec.PotentiallyReferenced) {
9102 // Mark any remaining declarations in the current position of the stack
9103 // as "referenced". If they were not meant to be referenced, semantic
9104 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009105 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00009106 I = Rec.PotentiallyReferenced->begin(),
9107 IEnd = Rec.PotentiallyReferenced->end();
9108 I != IEnd; ++I)
9109 MarkDeclarationReferenced(I->first, I->second);
9110 }
9111
9112 if (Rec.PotentiallyDiagnosed) {
9113 // Emit any pending diagnostics.
9114 for (PotentiallyEmittedDiagnostics::iterator
9115 I = Rec.PotentiallyDiagnosed->begin(),
9116 IEnd = Rec.PotentiallyDiagnosed->end();
9117 I != IEnd; ++I)
9118 Diag(I->first, I->second);
9119 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009120 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009121
9122 // When are coming out of an unevaluated context, clear out any
9123 // temporaries that we may have created as part of the evaluation of
9124 // the expression in that context: they aren't relevant because they
9125 // will never be constructed.
John McCallf85e1932011-06-15 23:02:42 +00009126 if (Rec.Context == Unevaluated) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009127 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9128 ExprTemporaries.end());
John McCallf85e1932011-06-15 23:02:42 +00009129 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9130
9131 // Otherwise, merge the contexts together.
9132 } else {
9133 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9134 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009135
9136 // Destroy the popped expression evaluation record.
9137 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009138}
Douglas Gregore0762c92009-06-19 23:52:42 +00009139
John McCallf85e1932011-06-15 23:02:42 +00009140void Sema::DiscardCleanupsInEvaluationContext() {
9141 ExprTemporaries.erase(
9142 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9143 ExprTemporaries.end());
9144 ExprNeedsCleanups = false;
9145}
9146
Douglas Gregore0762c92009-06-19 23:52:42 +00009147/// \brief Note that the given declaration was referenced in the source code.
9148///
9149/// This routine should be invoke whenever a given declaration is referenced
9150/// in the source code, and where that reference occurred. If this declaration
9151/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9152/// C99 6.9p3), then the declaration will be marked as used.
9153///
9154/// \param Loc the location where the declaration was referenced.
9155///
9156/// \param D the declaration that has been referenced by the source code.
9157void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9158 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009159
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +00009160 D->setReferenced();
9161
Douglas Gregorc070cc62010-06-17 23:14:26 +00009162 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009163 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009164
Richard Trieu67e29332011-08-02 04:35:43 +00009165 // Mark a parameter or variable declaration "used", regardless of whether
9166 // we're in a template or not. The reason for this is that unevaluated
9167 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9168 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009169 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009170 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009171 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009172 return;
9173 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009174
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009175 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9176 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009177
Douglas Gregore0762c92009-06-19 23:52:42 +00009178 // Do not mark anything as "used" within a dependent context; wait for
9179 // an instantiation.
9180 if (CurContext->isDependentContext())
9181 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009182
Douglas Gregor2afce722009-11-26 00:44:06 +00009183 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009184 case Unevaluated:
9185 // We are in an expression that is not potentially evaluated; do nothing.
9186 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009187
Douglas Gregorac7610d2009-06-22 20:57:11 +00009188 case PotentiallyEvaluated:
9189 // We are in a potentially-evaluated expression, so this declaration is
9190 // "used"; handle this below.
9191 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009192
Douglas Gregorac7610d2009-06-22 20:57:11 +00009193 case PotentiallyPotentiallyEvaluated:
9194 // We are in an expression that may be potentially evaluated; queue this
9195 // declaration reference until we know whether the expression is
9196 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009197 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009198 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009199
9200 case PotentiallyEvaluatedIfUsed:
9201 // Referenced declarations will only be used if the construct in the
9202 // containing expression is used.
9203 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009204 }
Mike Stump1eb44332009-09-09 15:08:12 +00009205
Douglas Gregore0762c92009-06-19 23:52:42 +00009206 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009207 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009208 if (Constructor->isDefaulted()) {
9209 if (Constructor->isDefaultConstructor()) {
9210 if (Constructor->isTrivial())
9211 return;
9212 if (!Constructor->isUsed(false))
9213 DefineImplicitDefaultConstructor(Loc, Constructor);
9214 } else if (Constructor->isCopyConstructor()) {
9215 if (!Constructor->isUsed(false))
9216 DefineImplicitCopyConstructor(Loc, Constructor);
9217 } else if (Constructor->isMoveConstructor()) {
9218 if (!Constructor->isUsed(false))
9219 DefineImplicitMoveConstructor(Loc, Constructor);
9220 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009221 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009222
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009223 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009224 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00009225 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009226 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009227 if (Destructor->isVirtual())
9228 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009229 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Sean Hunt2b188082011-05-14 05:23:28 +00009230 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009231 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009232 if (!MethodDecl->isUsed(false)) {
9233 if (MethodDecl->isCopyAssignmentOperator())
9234 DefineImplicitCopyAssignment(Loc, MethodDecl);
9235 else
9236 DefineImplicitMoveAssignment(Loc, MethodDecl);
9237 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009238 } else if (MethodDecl->isVirtual())
9239 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009240 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009241 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +00009242 // Recursive functions should be marked when used from another function.
9243 if (CurContext == Function) return;
9244
Mike Stump1eb44332009-09-09 15:08:12 +00009245 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009246 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009247 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009248 bool AlreadyInstantiated = false;
9249 if (FunctionTemplateSpecializationInfo *SpecInfo
9250 = Function->getTemplateSpecializationInfo()) {
9251 if (SpecInfo->getPointOfInstantiation().isInvalid())
9252 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009253 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009254 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009255 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009256 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009257 = Function->getMemberSpecializationInfo()) {
9258 if (MSInfo->getPointOfInstantiation().isInvalid())
9259 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009260 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009261 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009262 AlreadyInstantiated = true;
9263 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009264
Douglas Gregor60406be2010-01-16 22:29:39 +00009265 if (!AlreadyInstantiated) {
9266 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9267 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9268 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9269 Loc));
9270 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00009271 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00009272 }
John McCall15e310a2011-02-19 02:53:41 +00009273 } else {
9274 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +00009275 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9276 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00009277 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00009278 MarkDeclarationReferenced(Loc, *i);
9279 }
John McCall15e310a2011-02-19 02:53:41 +00009280 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009281
John McCall15e310a2011-02-19 02:53:41 +00009282 // Keep track of used but undefined functions.
9283 if (!Function->isPure() && !Function->hasBody() &&
9284 Function->getLinkage() != ExternalLinkage) {
9285 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9286 if (old.isInvalid()) old = Loc;
9287 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00009288
John McCall15e310a2011-02-19 02:53:41 +00009289 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +00009290 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009291 }
Mike Stump1eb44332009-09-09 15:08:12 +00009292
Douglas Gregore0762c92009-06-19 23:52:42 +00009293 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00009294 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00009295 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009296 Var->getInstantiatedFromStaticDataMember()) {
9297 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9298 assert(MSInfo && "Missing member specialization information?");
9299 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9300 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9301 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redlf79a7192011-04-29 08:19:30 +00009302 // This is a modification of an existing AST node. Notify listeners.
9303 if (ASTMutationListener *L = getASTMutationListener())
9304 L->StaticDataMemberInstantiated(Var);
Chandler Carruth62c78d52010-08-25 08:44:16 +00009305 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009306 }
9307 }
Mike Stump1eb44332009-09-09 15:08:12 +00009308
John McCall77efc682011-02-21 19:25:48 +00009309 // Keep track of used but undefined variables. We make a hole in
9310 // the warning for static const data members with in-line
9311 // initializers.
John McCall15e310a2011-02-19 02:53:41 +00009312 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall77efc682011-02-21 19:25:48 +00009313 && Var->getLinkage() != ExternalLinkage
9314 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall15e310a2011-02-19 02:53:41 +00009315 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9316 if (old.isInvalid()) old = Loc;
9317 }
Douglas Gregor7caa6822009-07-24 20:34:43 +00009318
Douglas Gregore0762c92009-06-19 23:52:42 +00009319 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00009320 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00009321 }
Douglas Gregore0762c92009-06-19 23:52:42 +00009322}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009323
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009324namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009325 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009326 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009327 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009328 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9329 Sema &S;
9330 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009331
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009332 public:
9333 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009334
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009335 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009336
9337 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9338 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009339 };
9340}
9341
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009342bool MarkReferencedDecls::TraverseTemplateArgument(
9343 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009344 if (Arg.getKind() == TemplateArgument::Declaration) {
9345 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9346 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009347
9348 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009349}
9350
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009351bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009352 if (ClassTemplateSpecializationDecl *Spec
9353 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9354 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +00009355 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009356 }
9357
Chandler Carruthe3e210c2010-06-10 10:31:57 +00009358 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009359}
9360
9361void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9362 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009363 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009364}
9365
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009366namespace {
9367 /// \brief Helper class that marks all of the declarations referenced by
9368 /// potentially-evaluated subexpressions as "referenced".
9369 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9370 Sema &S;
9371
9372 public:
9373 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9374
9375 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9376
9377 void VisitDeclRefExpr(DeclRefExpr *E) {
9378 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9379 }
9380
9381 void VisitMemberExpr(MemberExpr *E) {
9382 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009383 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009384 }
9385
9386 void VisitCXXNewExpr(CXXNewExpr *E) {
9387 if (E->getConstructor())
9388 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9389 if (E->getOperatorNew())
9390 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9391 if (E->getOperatorDelete())
9392 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009393 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009394 }
9395
9396 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9397 if (E->getOperatorDelete())
9398 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +00009399 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9400 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9401 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9402 S.MarkDeclarationReferenced(E->getLocStart(),
9403 S.LookupDestructor(Record));
9404 }
9405
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009406 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009407 }
9408
9409 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9410 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009411 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009412 }
9413
9414 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9415 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9416 }
Douglas Gregor102ff972010-10-19 17:17:35 +00009417
9418 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9419 Visit(E->getExpr());
9420 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009421 };
9422}
9423
9424/// \brief Mark any declarations that appear within this expression or any
9425/// potentially-evaluated subexpressions as "referenced".
9426void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9427 EvaluatedExprMarker(*this).Visit(E);
9428}
9429
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009430/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9431/// of the program being compiled.
9432///
9433/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009434/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009435/// possibility that the code will actually be executable. Code in sizeof()
9436/// expressions, code used only during overload resolution, etc., are not
9437/// potentially evaluated. This routine will suppress such diagnostics or,
9438/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009439/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009440/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009441///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009442/// This routine should be used for all diagnostics that describe the run-time
9443/// behavior of a program, such as passing a non-POD value through an ellipsis.
9444/// Failure to do so will likely result in spurious diagnostics or failures
9445/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek762696f2011-02-23 01:51:43 +00009446bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009447 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +00009448 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009449 case Unevaluated:
9450 // The argument will never be evaluated, so don't complain.
9451 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009452
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009453 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009454 case PotentiallyEvaluatedIfUsed:
Ted Kremenek351ba912011-02-23 01:52:04 +00009455 if (stmt && getCurFunctionOrMethodDecl()) {
9456 FunctionScopes.back()->PossiblyUnreachableDiags.
9457 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9458 }
9459 else
9460 Diag(Loc, PD);
9461
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009462 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009463
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009464 case PotentiallyPotentiallyEvaluated:
9465 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9466 break;
9467 }
9468
9469 return false;
9470}
9471
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009472bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9473 CallExpr *CE, FunctionDecl *FD) {
9474 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9475 return false;
9476
9477 PartialDiagnostic Note =
9478 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9479 << FD->getDeclName() : PDiag();
9480 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009481
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009482 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009483 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009484 PDiag(diag::err_call_function_incomplete_return)
9485 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009486 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009487 << CE->getSourceRange(),
9488 std::make_pair(NoteLoc, Note)))
9489 return true;
9490
9491 return false;
9492}
9493
Douglas Gregor92c3a042011-01-19 16:50:08 +00009494// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +00009495// will prevent this condition from triggering, which is what we want.
9496void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9497 SourceLocation Loc;
9498
John McCalla52ef082009-11-11 02:41:58 +00009499 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +00009500 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +00009501
Chandler Carruthb33c19f2011-08-16 22:30:10 +00009502 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +00009503 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +00009504 return;
9505
Douglas Gregor92c3a042011-01-19 16:50:08 +00009506 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9507
John McCallc8d8ac52009-11-12 00:06:05 +00009508 // Greylist some idioms by putting them into a warning subcategory.
9509 if (ObjCMessageExpr *ME
9510 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9511 Selector Sel = ME->getSelector();
9512
John McCallc8d8ac52009-11-12 00:06:05 +00009513 // self = [<foo> init...]
Douglas Gregor813d8342011-02-18 22:29:55 +00009514 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +00009515 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9516
9517 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +00009518 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +00009519 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9520 }
John McCalla52ef082009-11-11 02:41:58 +00009521
John McCall5a881bb2009-10-12 21:59:07 +00009522 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +00009523 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +00009524 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +00009525 return;
9526
Douglas Gregor92c3a042011-01-19 16:50:08 +00009527 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +00009528 Loc = Op->getOperatorLoc();
9529 } else {
9530 // Not an assignment.
9531 return;
9532 }
9533
Douglas Gregor55b38842010-04-14 16:09:52 +00009534 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +00009535
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009536 SourceLocation Open = E->getSourceRange().getBegin();
9537 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9538 Diag(Loc, diag::note_condition_assign_silence)
9539 << FixItHint::CreateInsertion(Open, "(")
9540 << FixItHint::CreateInsertion(Close, ")");
9541
Douglas Gregor92c3a042011-01-19 16:50:08 +00009542 if (IsOrAssign)
9543 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9544 << FixItHint::CreateReplacement(Loc, "!=");
9545 else
9546 Diag(Loc, diag::note_condition_assign_to_comparison)
9547 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +00009548}
9549
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009550/// \brief Redundant parentheses over an equality comparison can indicate
9551/// that the user intended an assignment used as condition.
9552void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009553 // Don't warn if the parens came from a macro.
9554 SourceLocation parenLoc = parenE->getLocStart();
9555 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9556 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +00009557 // Don't warn for dependent expressions.
9558 if (parenE->isTypeDependent())
9559 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009560
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009561 Expr *E = parenE->IgnoreParens();
9562
9563 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +00009564 if (opE->getOpcode() == BO_EQ &&
9565 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9566 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009567 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +00009568
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009569 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009570 Diag(Loc, diag::note_equality_comparison_silence)
9571 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9572 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009573 Diag(Loc, diag::note_equality_comparison_to_assign)
9574 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009575 }
9576}
9577
John Wiegley429bb272011-04-08 18:41:53 +00009578ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +00009579 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009580 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9581 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +00009582
John McCall864c0412011-04-26 20:42:42 +00009583 ExprResult result = CheckPlaceholderExpr(E);
9584 if (result.isInvalid()) return ExprError();
9585 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00009586
John McCall864c0412011-04-26 20:42:42 +00009587 if (!E->isTypeDependent()) {
John McCallf6a16482010-12-04 03:47:34 +00009588 if (getLangOptions().CPlusPlus)
9589 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9590
John Wiegley429bb272011-04-08 18:41:53 +00009591 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9592 if (ERes.isInvalid())
9593 return ExprError();
9594 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +00009595
9596 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +00009597 if (!T->isScalarType()) { // C99 6.8.4.1p1
9598 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9599 << T << E->getSourceRange();
9600 return ExprError();
9601 }
John McCall5a881bb2009-10-12 21:59:07 +00009602 }
9603
John Wiegley429bb272011-04-08 18:41:53 +00009604 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +00009605}
Douglas Gregor586596f2010-05-06 17:25:47 +00009606
John McCall60d7b3a2010-08-24 06:29:42 +00009607ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9608 Expr *Sub) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +00009609 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +00009610 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009611
9612 return CheckBooleanCondition(Sub, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +00009613}
John McCall2a984ca2010-10-12 00:20:44 +00009614
John McCall1de4d4e2011-04-07 08:22:57 +00009615namespace {
John McCall755d8492011-04-12 00:42:48 +00009616 /// A visitor for rebuilding a call to an __unknown_any expression
9617 /// to have an appropriate type.
9618 struct RebuildUnknownAnyFunction
9619 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9620
9621 Sema &S;
9622
9623 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9624
9625 ExprResult VisitStmt(Stmt *S) {
9626 llvm_unreachable("unexpected statement!");
9627 return ExprError();
9628 }
9629
9630 ExprResult VisitExpr(Expr *expr) {
9631 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
9632 << expr->getSourceRange();
9633 return ExprError();
9634 }
9635
9636 /// Rebuild an expression which simply semantically wraps another
9637 /// expression which it shares the type and value kind of.
9638 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9639 ExprResult subResult = Visit(expr->getSubExpr());
9640 if (subResult.isInvalid()) return ExprError();
9641
9642 Expr *subExpr = subResult.take();
9643 expr->setSubExpr(subExpr);
9644 expr->setType(subExpr->getType());
9645 expr->setValueKind(subExpr->getValueKind());
9646 assert(expr->getObjectKind() == OK_Ordinary);
9647 return expr;
9648 }
9649
9650 ExprResult VisitParenExpr(ParenExpr *paren) {
9651 return rebuildSugarExpr(paren);
9652 }
9653
9654 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9655 return rebuildSugarExpr(op);
9656 }
9657
9658 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9659 ExprResult subResult = Visit(op->getSubExpr());
9660 if (subResult.isInvalid()) return ExprError();
9661
9662 Expr *subExpr = subResult.take();
9663 op->setSubExpr(subExpr);
9664 op->setType(S.Context.getPointerType(subExpr->getType()));
9665 assert(op->getValueKind() == VK_RValue);
9666 assert(op->getObjectKind() == OK_Ordinary);
9667 return op;
9668 }
9669
9670 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
9671 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
9672
9673 expr->setType(decl->getType());
9674
9675 assert(expr->getValueKind() == VK_RValue);
9676 if (S.getLangOptions().CPlusPlus &&
9677 !(isa<CXXMethodDecl>(decl) &&
9678 cast<CXXMethodDecl>(decl)->isInstance()))
9679 expr->setValueKind(VK_LValue);
9680
9681 return expr;
9682 }
9683
9684 ExprResult VisitMemberExpr(MemberExpr *mem) {
9685 return resolveDecl(mem, mem->getMemberDecl());
9686 }
9687
9688 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
9689 return resolveDecl(ref, ref->getDecl());
9690 }
9691 };
9692}
9693
9694/// Given a function expression of unknown-any type, try to rebuild it
9695/// to have a function type.
9696static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
9697 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
9698 if (result.isInvalid()) return ExprError();
9699 return S.DefaultFunctionArrayConversion(result.take());
9700}
9701
9702namespace {
John McCall379b5152011-04-11 07:02:50 +00009703 /// A visitor for rebuilding an expression of type __unknown_anytype
9704 /// into one which resolves the type directly on the referring
9705 /// expression. Strict preservation of the original source
9706 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +00009707 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +00009708 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +00009709
9710 Sema &S;
9711
9712 /// The current destination type.
9713 QualType DestType;
9714
9715 RebuildUnknownAnyExpr(Sema &S, QualType castType)
9716 : S(S), DestType(castType) {}
9717
John McCalla5fc4722011-04-09 22:50:59 +00009718 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +00009719 llvm_unreachable("unexpected statement!");
John McCalla5fc4722011-04-09 22:50:59 +00009720 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009721 }
9722
John McCall379b5152011-04-11 07:02:50 +00009723 ExprResult VisitExpr(Expr *expr) {
9724 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9725 << expr->getSourceRange();
9726 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009727 }
9728
John McCall379b5152011-04-11 07:02:50 +00009729 ExprResult VisitCallExpr(CallExpr *call);
9730 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
9731
John McCalla5fc4722011-04-09 22:50:59 +00009732 /// Rebuild an expression which simply semantically wraps another
9733 /// expression which it shares the type and value kind of.
9734 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9735 ExprResult subResult = Visit(expr->getSubExpr());
John McCall755d8492011-04-12 00:42:48 +00009736 if (subResult.isInvalid()) return ExprError();
John McCalla5fc4722011-04-09 22:50:59 +00009737 Expr *subExpr = subResult.take();
9738 expr->setSubExpr(subExpr);
9739 expr->setType(subExpr->getType());
9740 expr->setValueKind(subExpr->getValueKind());
9741 assert(expr->getObjectKind() == OK_Ordinary);
9742 return expr;
9743 }
John McCall1de4d4e2011-04-07 08:22:57 +00009744
John McCalla5fc4722011-04-09 22:50:59 +00009745 ExprResult VisitParenExpr(ParenExpr *paren) {
9746 return rebuildSugarExpr(paren);
9747 }
9748
9749 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9750 return rebuildSugarExpr(op);
9751 }
9752
John McCall755d8492011-04-12 00:42:48 +00009753 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9754 const PointerType *ptr = DestType->getAs<PointerType>();
9755 if (!ptr) {
9756 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
9757 << op->getSourceRange();
9758 return ExprError();
9759 }
9760 assert(op->getValueKind() == VK_RValue);
9761 assert(op->getObjectKind() == OK_Ordinary);
9762 op->setType(DestType);
9763
9764 // Build the sub-expression as if it were an object of the pointee type.
9765 DestType = ptr->getPointeeType();
9766 ExprResult subResult = Visit(op->getSubExpr());
9767 if (subResult.isInvalid()) return ExprError();
9768 op->setSubExpr(subResult.take());
9769 return op;
9770 }
9771
John McCall379b5152011-04-11 07:02:50 +00009772 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCalla5fc4722011-04-09 22:50:59 +00009773
John McCall755d8492011-04-12 00:42:48 +00009774 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCalla5fc4722011-04-09 22:50:59 +00009775
John McCall755d8492011-04-12 00:42:48 +00009776 ExprResult VisitMemberExpr(MemberExpr *mem) {
9777 return resolveDecl(mem, mem->getMemberDecl());
9778 }
John McCalla5fc4722011-04-09 22:50:59 +00009779
9780 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall379b5152011-04-11 07:02:50 +00009781 return resolveDecl(ref, ref->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +00009782 }
9783 };
9784}
9785
John McCall379b5152011-04-11 07:02:50 +00009786/// Rebuilds a call expression which yielded __unknown_anytype.
9787ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
9788 Expr *callee = call->getCallee();
9789
9790 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +00009791 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +00009792 FK_FunctionPointer,
9793 FK_BlockPointer
9794 };
9795
9796 FnKind kind;
9797 QualType type = callee->getType();
John McCallf5307512011-04-27 00:36:17 +00009798 if (type == S.Context.BoundMemberTy) {
9799 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
9800 kind = FK_MemberFunction;
9801 type = Expr::findBoundMemberType(callee);
John McCall379b5152011-04-11 07:02:50 +00009802 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
9803 type = ptr->getPointeeType();
9804 kind = FK_FunctionPointer;
9805 } else {
9806 type = type->castAs<BlockPointerType>()->getPointeeType();
9807 kind = FK_BlockPointer;
9808 }
9809 const FunctionType *fnType = type->castAs<FunctionType>();
9810
9811 // Verify that this is a legal result type of a function.
9812 if (DestType->isArrayType() || DestType->isFunctionType()) {
9813 unsigned diagID = diag::err_func_returning_array_function;
9814 if (kind == FK_BlockPointer)
9815 diagID = diag::err_block_returning_array_function;
9816
9817 S.Diag(call->getExprLoc(), diagID)
9818 << DestType->isFunctionType() << DestType;
9819 return ExprError();
9820 }
9821
9822 // Otherwise, go ahead and set DestType as the call's result.
9823 call->setType(DestType.getNonLValueExprType(S.Context));
9824 call->setValueKind(Expr::getValueKindForType(DestType));
9825 assert(call->getObjectKind() == OK_Ordinary);
9826
9827 // Rebuild the function type, replacing the result type with DestType.
9828 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
9829 DestType = S.Context.getFunctionType(DestType,
9830 proto->arg_type_begin(),
9831 proto->getNumArgs(),
9832 proto->getExtProtoInfo());
9833 else
9834 DestType = S.Context.getFunctionNoProtoType(DestType,
9835 fnType->getExtInfo());
9836
9837 // Rebuild the appropriate pointer-to-function type.
9838 switch (kind) {
John McCallf5307512011-04-27 00:36:17 +00009839 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +00009840 // Nothing to do.
9841 break;
9842
9843 case FK_FunctionPointer:
9844 DestType = S.Context.getPointerType(DestType);
9845 break;
9846
9847 case FK_BlockPointer:
9848 DestType = S.Context.getBlockPointerType(DestType);
9849 break;
9850 }
9851
9852 // Finally, we can recurse.
9853 ExprResult calleeResult = Visit(callee);
9854 if (!calleeResult.isUsable()) return ExprError();
9855 call->setCallee(calleeResult.take());
9856
9857 // Bind a temporary if necessary.
9858 return S.MaybeBindToTemporary(call);
9859}
9860
9861ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall755d8492011-04-12 00:42:48 +00009862 // Verify that this is a legal result type of a call.
9863 if (DestType->isArrayType() || DestType->isFunctionType()) {
9864 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
9865 << DestType->isFunctionType() << DestType;
9866 return ExprError();
John McCall379b5152011-04-11 07:02:50 +00009867 }
9868
John McCall48218c62011-07-13 17:56:40 +00009869 // Rewrite the method result type if available.
9870 if (ObjCMethodDecl *method = msg->getMethodDecl()) {
9871 assert(method->getResultType() == S.Context.UnknownAnyTy);
9872 method->setResultType(DestType);
9873 }
John McCall755d8492011-04-12 00:42:48 +00009874
John McCall379b5152011-04-11 07:02:50 +00009875 // Change the type of the message.
John McCall755d8492011-04-12 00:42:48 +00009876 msg->setType(DestType.getNonReferenceType());
9877 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +00009878
John McCall755d8492011-04-12 00:42:48 +00009879 return S.MaybeBindToTemporary(msg);
John McCall379b5152011-04-11 07:02:50 +00009880}
9881
9882ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall755d8492011-04-12 00:42:48 +00009883 // The only case we should ever see here is a function-to-pointer decay.
John McCall379b5152011-04-11 07:02:50 +00009884 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall379b5152011-04-11 07:02:50 +00009885 assert(ice->getValueKind() == VK_RValue);
9886 assert(ice->getObjectKind() == OK_Ordinary);
9887
John McCall755d8492011-04-12 00:42:48 +00009888 ice->setType(DestType);
9889
John McCall379b5152011-04-11 07:02:50 +00009890 // Rebuild the sub-expression as the pointee (function) type.
9891 DestType = DestType->castAs<PointerType>()->getPointeeType();
9892
9893 ExprResult result = Visit(ice->getSubExpr());
9894 if (!result.isUsable()) return ExprError();
9895
9896 ice->setSubExpr(result.take());
9897 return S.Owned(ice);
9898}
9899
John McCall755d8492011-04-12 00:42:48 +00009900ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall379b5152011-04-11 07:02:50 +00009901 ExprValueKind valueKind = VK_LValue;
John McCall379b5152011-04-11 07:02:50 +00009902 QualType type = DestType;
9903
9904 // We know how to make this work for certain kinds of decls:
9905
9906 // - functions
John McCall755d8492011-04-12 00:42:48 +00009907 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCalla19950e2011-08-10 04:12:23 +00009908 if (const PointerType *ptr = type->getAs<PointerType>()) {
9909 DestType = ptr->getPointeeType();
9910 ExprResult result = resolveDecl(expr, decl);
9911 if (result.isInvalid()) return ExprError();
9912 return S.ImpCastExprToType(result.take(), type,
9913 CK_FunctionToPointerDecay, VK_RValue);
9914 }
9915
9916 if (!type->isFunctionType()) {
9917 S.Diag(expr->getExprLoc(), diag::err_unknown_any_function)
9918 << decl << expr->getSourceRange();
9919 return ExprError();
9920 }
John McCall379b5152011-04-11 07:02:50 +00009921
John McCallf5307512011-04-27 00:36:17 +00009922 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
9923 if (method->isInstance()) {
9924 valueKind = VK_RValue;
9925 type = S.Context.BoundMemberTy;
9926 }
9927
John McCall379b5152011-04-11 07:02:50 +00009928 // Function references aren't l-values in C.
9929 if (!S.getLangOptions().CPlusPlus)
9930 valueKind = VK_RValue;
9931
9932 // - variables
9933 } else if (isa<VarDecl>(decl)) {
John McCall755d8492011-04-12 00:42:48 +00009934 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
9935 type = refTy->getPointeeType();
John McCall379b5152011-04-11 07:02:50 +00009936 } else if (type->isFunctionType()) {
John McCall755d8492011-04-12 00:42:48 +00009937 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
9938 << decl << expr->getSourceRange();
9939 return ExprError();
John McCall379b5152011-04-11 07:02:50 +00009940 }
9941
9942 // - nothing else
9943 } else {
9944 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9945 << decl << expr->getSourceRange();
9946 return ExprError();
9947 }
9948
John McCall755d8492011-04-12 00:42:48 +00009949 decl->setType(DestType);
9950 expr->setType(type);
9951 expr->setValueKind(valueKind);
9952 return S.Owned(expr);
John McCall379b5152011-04-11 07:02:50 +00009953}
9954
John McCall1de4d4e2011-04-07 08:22:57 +00009955/// Check a cast of an unknown-any type. We intentionally only
9956/// trigger this for C-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00009957ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
9958 Expr *castExpr, CastKind &castKind,
9959 ExprValueKind &VK, CXXCastPath &path) {
John McCall1de4d4e2011-04-07 08:22:57 +00009960 // Rewrite the casted expression from scratch.
John McCalla5fc4722011-04-09 22:50:59 +00009961 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
9962 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009963
John McCalla5fc4722011-04-09 22:50:59 +00009964 castExpr = result.take();
9965 VK = castExpr->getValueKind();
9966 castKind = CK_NoOp;
9967
9968 return castExpr;
John McCall1de4d4e2011-04-07 08:22:57 +00009969}
9970
9971static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
9972 Expr *orig = e;
John McCall379b5152011-04-11 07:02:50 +00009973 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +00009974 while (true) {
9975 e = e->IgnoreParenImpCasts();
John McCall379b5152011-04-11 07:02:50 +00009976 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall1de4d4e2011-04-07 08:22:57 +00009977 e = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +00009978 diagID = diag::err_uncasted_call_of_unknown_any;
9979 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00009980 break;
John McCall379b5152011-04-11 07:02:50 +00009981 }
John McCall1de4d4e2011-04-07 08:22:57 +00009982 }
9983
John McCall379b5152011-04-11 07:02:50 +00009984 SourceLocation loc;
9985 NamedDecl *d;
9986 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9987 loc = ref->getLocation();
9988 d = ref->getDecl();
9989 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
9990 loc = mem->getMemberLoc();
9991 d = mem->getMemberDecl();
9992 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
9993 diagID = diag::err_uncasted_call_of_unknown_any;
9994 loc = msg->getSelectorLoc();
9995 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +00009996 if (!d) {
9997 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
9998 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
9999 << orig->getSourceRange();
10000 return ExprError();
10001 }
John McCall379b5152011-04-11 07:02:50 +000010002 } else {
10003 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10004 << e->getSourceRange();
10005 return ExprError();
10006 }
10007
10008 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000010009
10010 // Never recoverable.
10011 return ExprError();
10012}
10013
John McCall2a984ca2010-10-12 00:20:44 +000010014/// Check for operands with placeholder types and complain if found.
10015/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000010016ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall1de4d4e2011-04-07 08:22:57 +000010017 // Placeholder types are always *exactly* the appropriate builtin type.
10018 QualType type = E->getType();
John McCall2a984ca2010-10-12 00:20:44 +000010019
John McCall1de4d4e2011-04-07 08:22:57 +000010020 // Overloaded expressions.
10021 if (type == Context.OverloadTy)
10022 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregordb2eae62011-03-16 19:16:25 +000010023 E->getSourceRange(),
John McCall1de4d4e2011-04-07 08:22:57 +000010024 QualType(),
10025 diag::err_ovl_unresolvable);
10026
John McCall864c0412011-04-26 20:42:42 +000010027 // Bound member functions.
10028 if (type == Context.BoundMemberTy) {
10029 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10030 << E->getSourceRange();
10031 return ExprError();
10032 }
10033
John McCall1de4d4e2011-04-07 08:22:57 +000010034 // Expressions of unknown type.
10035 if (type == Context.UnknownAnyTy)
10036 return diagnoseUnknownAnyExpr(*this, E);
10037
10038 assert(!type->isPlaceholderType());
10039 return Owned(E);
John McCall2a984ca2010-10-12 00:20:44 +000010040}
Richard Trieubb9b80c2011-04-21 21:44:26 +000010041
10042bool Sema::CheckCaseExpression(Expr *expr) {
10043 if (expr->isTypeDependent())
10044 return true;
10045 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
10046 return expr->getType()->isIntegralOrEnumerationType();
10047 return false;
10048}