blob: f10bb3413cbfa8e7938859e20893b8aee72d1dd2 [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
Richard Trieuccd891a2011-09-09 01:45:06 +0000265SourceRange Sema::getExprRange(Expr *E) const {
266 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000267}
268
Chris Lattnere7a2e912008-07-25 21:10:04 +0000269//===----------------------------------------------------------------------===//
270// Standard Promotions and Conversions
271//===----------------------------------------------------------------------===//
272
Chris Lattnere7a2e912008-07-25 21:10:04 +0000273/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000274ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000275 QualType Ty = E->getType();
276 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
277
Chris Lattnere7a2e912008-07-25 21:10:04 +0000278 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000279 E = ImpCastExprToType(E, Context.getPointerType(Ty),
280 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000281 else if (Ty->isArrayType()) {
282 // In C90 mode, arrays only promote to pointers if the array expression is
283 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
284 // type 'array of type' is converted to an expression that has type 'pointer
285 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
286 // that has type 'array of type' ...". The relevant change is "an lvalue"
287 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000288 //
289 // C++ 4.2p1:
290 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
291 // T" can be converted to an rvalue of type "pointer to T".
292 //
John McCall7eb0a9e2010-11-24 05:12:34 +0000293 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000294 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
295 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000296 }
John Wiegley429bb272011-04-08 18:41:53 +0000297 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000298}
299
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000300static void CheckForNullPointerDereference(Sema &S, Expr *E) {
301 // Check to see if we are dereferencing a null pointer. If so,
302 // and if not volatile-qualified, this is undefined behavior that the
303 // optimizer will delete, so warn about it. People sometimes try to use this
304 // to get a deterministic trap and are surprised by clang's behavior. This
305 // only handles the pattern "*null", which is a very syntactic check.
306 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
307 if (UO->getOpcode() == UO_Deref &&
308 UO->getSubExpr()->IgnoreParenCasts()->
309 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
310 !UO->getType().isVolatileQualified()) {
311 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
312 S.PDiag(diag::warn_indirection_through_null)
313 << UO->getSubExpr()->getSourceRange());
314 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
315 S.PDiag(diag::note_indirection_through_null));
316 }
317}
318
John Wiegley429bb272011-04-08 18:41:53 +0000319ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000320 // C++ [conv.lval]p1:
321 // A glvalue of a non-function, non-array type T can be
322 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000323 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000324
John McCall409fa9a2010-12-06 20:48:59 +0000325 QualType T = E->getType();
326 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000327
John McCall409fa9a2010-12-06 20:48:59 +0000328 // Create a load out of an ObjCProperty l-value, if necessary.
329 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +0000330 ExprResult Res = ConvertPropertyForRValue(E);
331 if (Res.isInvalid())
332 return Owned(E);
333 E = Res.take();
John McCall409fa9a2010-12-06 20:48:59 +0000334 if (!E->isGLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000335 return Owned(E);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000336 }
John McCall409fa9a2010-12-06 20:48:59 +0000337
338 // We don't want to throw lvalue-to-rvalue casts on top of
339 // expressions of certain types in C++.
340 if (getLangOptions().CPlusPlus &&
341 (E->getType() == Context.OverloadTy ||
342 T->isDependentType() ||
343 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000344 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000345
346 // The C standard is actually really unclear on this point, and
347 // DR106 tells us what the result should be but not why. It's
348 // generally best to say that void types just doesn't undergo
349 // lvalue-to-rvalue at all. Note that expressions of unqualified
350 // 'void' type are never l-values, but qualified void can be.
351 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000352 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000353
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000354 CheckForNullPointerDereference(*this, E);
355
John McCall409fa9a2010-12-06 20:48:59 +0000356 // C++ [conv.lval]p1:
357 // [...] If T is a non-class type, the type of the prvalue is the
358 // cv-unqualified version of T. Otherwise, the type of the
359 // rvalue is T.
360 //
361 // C99 6.3.2.1p2:
362 // If the lvalue has qualified type, the value has the unqualified
363 // version of the type of the lvalue; otherwise, the value has the
364 // type of the lvalue.
365 if (T.hasQualifiers())
366 T = T.getUnqualifiedType();
Ted Kremeneka0125d82011-02-16 01:57:07 +0000367
John Wiegley429bb272011-04-08 18:41:53 +0000368 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
369 E, 0, VK_RValue));
John McCall409fa9a2010-12-06 20:48:59 +0000370}
371
John Wiegley429bb272011-04-08 18:41:53 +0000372ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
373 ExprResult Res = DefaultFunctionArrayConversion(E);
374 if (Res.isInvalid())
375 return ExprError();
376 Res = DefaultLvalueConversion(Res.take());
377 if (Res.isInvalid())
378 return ExprError();
379 return move(Res);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000380}
381
382
Chris Lattnere7a2e912008-07-25 21:10:04 +0000383/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000384/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000385/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000386/// apply if the array is an argument to the sizeof or address (&) operators.
387/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000388ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000389 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000390 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
391 if (Res.isInvalid())
392 return Owned(E);
393 E = Res.take();
John McCall0ae287a2010-12-01 04:43:34 +0000394
395 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000396 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCall0ae287a2010-12-01 04:43:34 +0000397
398 // Try to perform integral promotions if the object has a theoretically
399 // promotable type.
400 if (Ty->isIntegralOrUnscopedEnumerationType()) {
401 // C99 6.3.1.1p2:
402 //
403 // The following may be used in an expression wherever an int or
404 // unsigned int may be used:
405 // - an object or expression with an integer type whose integer
406 // conversion rank is less than or equal to the rank of int
407 // and unsigned int.
408 // - A bit-field of type _Bool, int, signed int, or unsigned int.
409 //
410 // If an int can represent all values of the original type, the
411 // value is converted to an int; otherwise, it is converted to an
412 // unsigned int. These are called the integer promotions. All
413 // other types are unchanged by the integer promotions.
414
415 QualType PTy = Context.isPromotableBitField(E);
416 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000417 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
418 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000419 }
420 if (Ty->isPromotableIntegerType()) {
421 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000422 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
423 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000424 }
Eli Friedman04e83572009-08-20 04:21:42 +0000425 }
John Wiegley429bb272011-04-08 18:41:53 +0000426 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000427}
428
Chris Lattner05faf172008-07-25 22:25:12 +0000429/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000430/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000431/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000432ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
433 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000434 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000435
John Wiegley429bb272011-04-08 18:41:53 +0000436 ExprResult Res = UsualUnaryConversions(E);
437 if (Res.isInvalid())
438 return Owned(E);
439 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000440
Chris Lattner05faf172008-07-25 22:25:12 +0000441 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000442 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000443 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
444
John McCall96a914a2011-08-27 22:06:17 +0000445 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-08-29 23:55:37 +0000446 // promotion, even on class types, but note:
447 // C++11 [conv.lval]p2:
448 // When an lvalue-to-rvalue conversion occurs in an unevaluated
449 // operand or a subexpression thereof the value contained in the
450 // referenced object is not accessed. Otherwise, if the glvalue
451 // has a class type, the conversion copy-initializes a temporary
452 // of type T from the glvalue and the result of the conversion
453 // is a prvalue for the temporary.
454 // FIXME: add some way to gate this entire thing for correctness in
455 // potentially potentially evaluated contexts.
John McCall96a914a2011-08-27 22:06:17 +0000456 if (getLangOptions().CPlusPlus && E->isGLValue() &&
457 ExprEvalContexts.back().Context != Unevaluated) {
John McCall5f8d6042011-08-27 01:09:30 +0000458 ExprResult Temp = PerformCopyInitialization(
459 InitializedEntity::InitializeTemporary(E->getType()),
460 E->getExprLoc(),
461 Owned(E));
462 if (Temp.isInvalid())
463 return ExprError();
464 E = Temp.get();
465 }
466
John Wiegley429bb272011-04-08 18:41:53 +0000467 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000468}
469
Chris Lattner312531a2009-04-12 08:11:20 +0000470/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
471/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley429bb272011-04-08 18:41:53 +0000472/// interfaces passed by value.
473ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000474 FunctionDecl *FDecl) {
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000475 ExprResult ExprRes = CheckPlaceholderExpr(E);
476 if (ExprRes.isInvalid())
477 return ExprError();
478
479 ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000480 if (ExprRes.isInvalid())
481 return ExprError();
482 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000484 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley429bb272011-04-08 18:41:53 +0000485 if (E->getType()->isObjCObjectType() &&
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000486 DiagRuntimeBehavior(E->getLocStart(), 0,
487 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
488 << E->getType() << CT))
John Wiegley429bb272011-04-08 18:41:53 +0000489 return ExprError();
John McCall5f8d6042011-08-27 01:09:30 +0000490
John McCallf85e1932011-06-15 23:02:42 +0000491 if (!E->getType().isPODType(Context)) {
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000492 // C++0x [expr.call]p7:
493 // Passing a potentially-evaluated argument of class type (Clause 9)
494 // having a non-trivial copy constructor, a non-trivial move constructor,
495 // or a non-trivial destructor, with no corresponding parameter,
496 // is conditionally-supported with implementation-defined semantics.
497 bool TrivialEnough = false;
498 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
499 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
500 if (Record->hasTrivialCopyConstructor() &&
501 Record->hasTrivialMoveConstructor() &&
502 Record->hasTrivialDestructor())
503 TrivialEnough = true;
504 }
505 }
John McCallf85e1932011-06-15 23:02:42 +0000506
507 if (!TrivialEnough &&
508 getLangOptions().ObjCAutoRefCount &&
509 E->getType()->isObjCLifetimeType())
510 TrivialEnough = true;
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000511
512 if (TrivialEnough) {
513 // Nothing to diagnose. This is okay.
514 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000515 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000516 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000517 << CT)) {
518 // Turn this into a trap.
519 CXXScopeSpec SS;
520 UnqualifiedId Name;
521 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
522 E->getLocStart());
523 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
524 if (TrapFn.isInvalid())
525 return ExprError();
526
527 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
528 MultiExprArg(), E->getLocEnd());
529 if (Call.isInvalid())
530 return ExprError();
531
532 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
533 Call.get(), E);
534 if (Comma.isInvalid())
John McCall66c20302011-08-26 18:41:18 +0000535 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000536 E = Comma.get();
537 }
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000538 }
539
John Wiegley429bb272011-04-08 18:41:53 +0000540 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000541}
542
Richard Trieu8289f492011-09-02 20:58:51 +0000543/// \brief Converts an integer to complex float type. Helper function of
544/// UsualArithmeticConversions()
545///
546/// \return false if the integer expression is an integer type and is
547/// successfully converted to the complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000548static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
549 ExprResult &ComplexExpr,
550 QualType IntTy,
551 QualType ComplexTy,
552 bool SkipCast) {
553 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
554 if (SkipCast) return false;
555 if (IntTy->isIntegerType()) {
556 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
557 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
558 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000559 CK_FloatingRealToComplex);
560 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +0000561 assert(IntTy->isComplexIntegerType());
562 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000563 CK_IntegralComplexToFloatingComplex);
564 }
565 return false;
566}
567
568/// \brief Takes two complex float types and converts them to the same type.
569/// Helper function of UsualArithmeticConversions()
570static QualType
Richard Trieucafd30b2011-09-06 18:25:09 +0000571handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
572 ExprResult &RHS, QualType LHSType,
573 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000574 bool IsCompAssign) {
Richard Trieucafd30b2011-09-06 18:25:09 +0000575 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000576
577 if (order < 0) {
578 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000579 if (!IsCompAssign)
Richard Trieucafd30b2011-09-06 18:25:09 +0000580 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
581 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000582 }
583 if (order > 0)
584 // _Complex float -> _Complex double
Richard Trieucafd30b2011-09-06 18:25:09 +0000585 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
586 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000587}
588
589/// \brief Converts otherExpr to complex float and promotes complexExpr if
590/// necessary. Helper function of UsualArithmeticConversions()
591static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuccd891a2011-09-09 01:45:06 +0000592 ExprResult &ComplexExpr,
593 ExprResult &OtherExpr,
594 QualType ComplexTy,
595 QualType OtherTy,
596 bool ConvertComplexExpr,
597 bool ConvertOtherExpr) {
598 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000599
600 // If just the complexExpr is complex, the otherExpr needs to be converted,
601 // and the complexExpr might need to be promoted.
602 if (order > 0) { // complexExpr is wider
603 // float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000604 if (ConvertOtherExpr) {
605 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
606 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
607 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000608 CK_FloatingRealToComplex);
609 }
Richard Trieuccd891a2011-09-09 01:45:06 +0000610 return ComplexTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000611 }
612
613 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000614 QualType result = (order == 0 ? ComplexTy :
615 S.Context.getComplexType(OtherTy));
Richard Trieu8289f492011-09-02 20:58:51 +0000616
617 // double -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000618 if (ConvertOtherExpr)
619 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000620 CK_FloatingRealToComplex);
621
622 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000623 if (ConvertComplexExpr && order < 0)
624 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000625 CK_FloatingComplexCast);
626
627 return result;
628}
629
630/// \brief Handle arithmetic conversion with complex types. Helper function of
631/// UsualArithmeticConversions()
Richard Trieucafd30b2011-09-06 18:25:09 +0000632static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
633 ExprResult &RHS, QualType LHSType,
634 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000635 bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000636 // if we have an integer operand, the result is the complex type.
Richard Trieucafd30b2011-09-06 18:25:09 +0000637 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000638 /*skipCast*/false))
Richard Trieucafd30b2011-09-06 18:25:09 +0000639 return LHSType;
640 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000641 /*skipCast*/IsCompAssign))
Richard Trieucafd30b2011-09-06 18:25:09 +0000642 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000643
644 // This handles complex/complex, complex/float, or float/complex.
645 // When both operands are complex, the shorter operand is converted to the
646 // type of the longer, and that is the type of the result. This corresponds
647 // to what is done when combining two real floating-point operands.
648 // The fun begins when size promotion occur across type domains.
649 // From H&S 6.3.4: When one operand is complex and the other is a real
650 // floating-point type, the less precise type is converted, within it's
651 // real or complex domain, to the precision of the other type. For example,
652 // when combining a "long double" with a "double _Complex", the
653 // "double _Complex" is promoted to "long double _Complex".
654
Richard Trieucafd30b2011-09-06 18:25:09 +0000655 bool LHSComplexFloat = LHSType->isComplexType();
656 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu8289f492011-09-02 20:58:51 +0000657
658 // If both are complex, just cast to the more precise type.
659 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieucafd30b2011-09-06 18:25:09 +0000660 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
661 LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000662 IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000663
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(
Richard Trieuccd891a2011-09-09 01:45:06 +0000668 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000669 /*convertOtherExpr*/ true);
670
671 assert(RHSComplexFloat);
672 return handleOtherComplexFloatConversion(
Richard Trieucafd30b2011-09-06 18:25:09 +0000673 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000674 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000675}
676
677/// \brief Hande arithmetic conversion from integer to float. Helper function
678/// of UsualArithmeticConversions()
Richard Trieuccd891a2011-09-09 01:45:06 +0000679static 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)
Richard Trieu8289f492011-09-02 20:58:51 +0000685 // Convert intExpr to the lhs floating point type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000686 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000687 CK_IntegralToFloating);
Richard Trieuccd891a2011-09-09 01:45:06 +0000688 return FloatTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000689 }
690
691 // Convert both sides to the appropriate complex float.
Richard Trieuccd891a2011-09-09 01:45:06 +0000692 assert(IntTy->isComplexIntegerType());
693 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000694
695 // _Complex int -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000696 if (ConvertInt)
697 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000698 CK_IntegralComplexToFloatingComplex);
699
700 // float -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000701 if (ConvertFloat)
702 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000703 CK_FloatingRealToComplex);
704
705 return result;
706}
707
708/// \brief Handle arithmethic conversion with floating point types. Helper
709/// function of UsualArithmeticConversions()
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000710static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
711 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000712 QualType RHSType, bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000713 bool LHSFloat = LHSType->isRealFloatingType();
714 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu8289f492011-09-02 20:58:51 +0000715
716 // If we have two real floating types, convert the smaller operand
717 // to the bigger result.
718 if (LHSFloat && RHSFloat) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000719 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000720 if (order > 0) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000721 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
722 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000723 }
724
725 assert(order < 0 && "illegal float comparison");
Richard Trieuccd891a2011-09-09 01:45:06 +0000726 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000727 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
728 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000729 }
730
731 if (LHSFloat)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000732 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000733 /*convertFloat=*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000734 /*convertInt=*/ true);
735 assert(RHSFloat);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000736 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000737 /*convertInt=*/ true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000738 /*convertFloat=*/!IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000739}
740
741/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000742/// of UsualArithmeticConversions()
Richard Trieu8289f492011-09-02 20:58:51 +0000743// FIXME: if the operands are (int, _Complex long), we currently
744// don't promote the complex. Also, signedness?
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000745static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
746 ExprResult &RHS, QualType LHSType,
747 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000748 bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000749 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
750 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu8289f492011-09-02 20:58:51 +0000751
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000752 if (LHSComplexInt && RHSComplexInt) {
753 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
754 RHSComplexInt->getElementType());
Richard Trieu8289f492011-09-02 20:58:51 +0000755 assert(order && "inequal types with equal element ordering");
756 if (order > 0) {
757 // _Complex int -> _Complex long
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000758 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
759 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000760 }
761
Richard Trieuccd891a2011-09-09 01:45:06 +0000762 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000763 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
764 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000765 }
766
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000767 if (LHSComplexInt) {
Richard Trieu8289f492011-09-02 20:58:51 +0000768 // int -> _Complex int
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000769 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
770 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000771 }
772
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000773 assert(RHSComplexInt);
Richard Trieu8289f492011-09-02 20:58:51 +0000774 // int -> _Complex int
Richard Trieuccd891a2011-09-09 01:45:06 +0000775 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000776 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
777 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000778}
779
780/// \brief Handle integer arithmetic conversions. Helper function of
781/// UsualArithmeticConversions()
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000782static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
783 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000784 QualType RHSType, bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000785 // The rules for this case are in C99 6.3.1.8
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000786 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
787 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
788 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
789 if (LHSSigned == RHSSigned) {
Richard Trieu8289f492011-09-02 20:58:51 +0000790 // Same signedness; use the higher-ranked type
791 if (order >= 0) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000792 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
793 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000794 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000795 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
796 return RHSType;
797 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000798 // The unsigned type has greater than or equal rank to the
799 // signed type, so use the unsigned type
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000800 if (RHSSigned) {
801 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
802 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000803 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000804 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
805 return RHSType;
806 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000807 // The two types are different widths; if we are here, that
808 // means the signed type is larger than the unsigned type, so
809 // use the signed type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000810 if (LHSSigned) {
811 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
812 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000813 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000814 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
815 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000816 } else {
817 // The signed type is higher-ranked than the unsigned type,
818 // but isn't actually any bigger (like unsigned int and long
819 // on most 32-bit systems). Use the unsigned type corresponding
820 // to the signed type.
821 QualType result =
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000822 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
823 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuccd891a2011-09-09 01:45:06 +0000824 if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000825 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu8289f492011-09-02 20:58:51 +0000826 return result;
827 }
828}
829
Chris Lattnere7a2e912008-07-25 21:10:04 +0000830/// UsualArithmeticConversions - Performs various conversions that are common to
831/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000832/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000833/// responsible for emitting appropriate error diagnostics.
834/// FIXME: verify the conversion rules for "complex int" are consistent with
835/// GCC.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000836QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +0000837 bool IsCompAssign) {
838 if (!IsCompAssign) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000839 LHS = UsualUnaryConversions(LHS.take());
840 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000841 return QualType();
842 }
Eli Friedmanab3a8522009-03-28 01:22:36 +0000843
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000844 RHS = UsualUnaryConversions(RHS.take());
845 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000846 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000847
Mike Stump1eb44332009-09-09 15:08:12 +0000848 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000849 // For example, "const float" and "float" are equivalent.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000850 QualType LHSType =
851 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
852 QualType RHSType =
853 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000854
855 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000856 if (LHSType == RHSType)
857 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000858
859 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
860 // The caller can deal with this (e.g. pointer + int).
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000861 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
862 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000863
John McCallcf33b242010-11-13 08:17:45 +0000864 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000865 QualType LHSUnpromotedType = LHSType;
866 if (LHSType->isPromotableIntegerType())
867 LHSType = Context.getPromotedIntegerType(LHSType);
868 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +0000869 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000870 LHSType = LHSBitfieldPromoteTy;
Richard Trieuccd891a2011-09-09 01:45:06 +0000871 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000872 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000873
John McCallcf33b242010-11-13 08:17:45 +0000874 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000875 if (LHSType == RHSType)
876 return LHSType;
John McCallcf33b242010-11-13 08:17:45 +0000877
878 // At this point, we have two different arithmetic types.
879
880 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000881 if (LHSType->isComplexType() || RHSType->isComplexType())
882 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000883 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000884
885 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000886 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
887 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000888 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000889
890 // Handle GCC complex int extension.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000891 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000892 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000893 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000894
895 // Finally, we have two differing integer types.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000896 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000897 IsCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000898}
899
Chris Lattnere7a2e912008-07-25 21:10:04 +0000900//===----------------------------------------------------------------------===//
901// Semantic Analysis for various Expression Types
902//===----------------------------------------------------------------------===//
903
904
Peter Collingbournef111d932011-04-15 00:35:48 +0000905ExprResult
906Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
907 SourceLocation DefaultLoc,
908 SourceLocation RParenLoc,
909 Expr *ControllingExpr,
Richard Trieuccd891a2011-09-09 01:45:06 +0000910 MultiTypeArg ArgTypes,
911 MultiExprArg ArgExprs) {
912 unsigned NumAssocs = ArgTypes.size();
913 assert(NumAssocs == ArgExprs.size());
Peter Collingbournef111d932011-04-15 00:35:48 +0000914
Richard Trieuccd891a2011-09-09 01:45:06 +0000915 ParsedType *ParsedTypes = ArgTypes.release();
916 Expr **Exprs = ArgExprs.release();
Peter Collingbournef111d932011-04-15 00:35:48 +0000917
918 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
919 for (unsigned i = 0; i < NumAssocs; ++i) {
920 if (ParsedTypes[i])
921 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
922 else
923 Types[i] = 0;
924 }
925
926 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
927 ControllingExpr, Types, Exprs,
928 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +0000929 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +0000930 return ER;
931}
932
933ExprResult
934Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
935 SourceLocation DefaultLoc,
936 SourceLocation RParenLoc,
937 Expr *ControllingExpr,
938 TypeSourceInfo **Types,
939 Expr **Exprs,
940 unsigned NumAssocs) {
941 bool TypeErrorFound = false,
942 IsResultDependent = ControllingExpr->isTypeDependent(),
943 ContainsUnexpandedParameterPack
944 = ControllingExpr->containsUnexpandedParameterPack();
945
946 for (unsigned i = 0; i < NumAssocs; ++i) {
947 if (Exprs[i]->containsUnexpandedParameterPack())
948 ContainsUnexpandedParameterPack = true;
949
950 if (Types[i]) {
951 if (Types[i]->getType()->containsUnexpandedParameterPack())
952 ContainsUnexpandedParameterPack = true;
953
954 if (Types[i]->getType()->isDependentType()) {
955 IsResultDependent = true;
956 } else {
957 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
958 // complete object type other than a variably modified type."
959 unsigned D = 0;
960 if (Types[i]->getType()->isIncompleteType())
961 D = diag::err_assoc_type_incomplete;
962 else if (!Types[i]->getType()->isObjectType())
963 D = diag::err_assoc_type_nonobject;
964 else if (Types[i]->getType()->isVariablyModifiedType())
965 D = diag::err_assoc_type_variably_modified;
966
967 if (D != 0) {
968 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
969 << Types[i]->getTypeLoc().getSourceRange()
970 << Types[i]->getType();
971 TypeErrorFound = true;
972 }
973
974 // C1X 6.5.1.1p2 "No two generic associations in the same generic
975 // selection shall specify compatible types."
976 for (unsigned j = i+1; j < NumAssocs; ++j)
977 if (Types[j] && !Types[j]->getType()->isDependentType() &&
978 Context.typesAreCompatible(Types[i]->getType(),
979 Types[j]->getType())) {
980 Diag(Types[j]->getTypeLoc().getBeginLoc(),
981 diag::err_assoc_compatible_types)
982 << Types[j]->getTypeLoc().getSourceRange()
983 << Types[j]->getType()
984 << Types[i]->getType();
985 Diag(Types[i]->getTypeLoc().getBeginLoc(),
986 diag::note_compat_assoc)
987 << Types[i]->getTypeLoc().getSourceRange()
988 << Types[i]->getType();
989 TypeErrorFound = true;
990 }
991 }
992 }
993 }
994 if (TypeErrorFound)
995 return ExprError();
996
997 // If we determined that the generic selection is result-dependent, don't
998 // try to compute the result expression.
999 if (IsResultDependent)
1000 return Owned(new (Context) GenericSelectionExpr(
1001 Context, KeyLoc, ControllingExpr,
1002 Types, Exprs, NumAssocs, DefaultLoc,
1003 RParenLoc, ContainsUnexpandedParameterPack));
1004
Chris Lattner5f9e2722011-07-23 10:55:15 +00001005 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +00001006 unsigned DefaultIndex = -1U;
1007 for (unsigned i = 0; i < NumAssocs; ++i) {
1008 if (!Types[i])
1009 DefaultIndex = i;
1010 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1011 Types[i]->getType()))
1012 CompatIndices.push_back(i);
1013 }
1014
1015 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
1016 // type compatible with at most one of the types named in its generic
1017 // association list."
1018 if (CompatIndices.size() > 1) {
1019 // We strip parens here because the controlling expression is typically
1020 // parenthesized in macro definitions.
1021 ControllingExpr = ControllingExpr->IgnoreParens();
1022 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1023 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1024 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001025 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001026 E = CompatIndices.end(); I != E; ++I) {
1027 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1028 diag::note_compat_assoc)
1029 << Types[*I]->getTypeLoc().getSourceRange()
1030 << Types[*I]->getType();
1031 }
1032 return ExprError();
1033 }
1034
1035 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
1036 // its controlling expression shall have type compatible with exactly one of
1037 // the types named in its generic association list."
1038 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1039 // We strip parens here because the controlling expression is typically
1040 // parenthesized in macro definitions.
1041 ControllingExpr = ControllingExpr->IgnoreParens();
1042 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1043 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1044 return ExprError();
1045 }
1046
1047 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1048 // type name that is compatible with the type of the controlling expression,
1049 // then the result expression of the generic selection is the expression
1050 // in that generic association. Otherwise, the result expression of the
1051 // generic selection is the expression in the default generic association."
1052 unsigned ResultIndex =
1053 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1054
1055 return Owned(new (Context) GenericSelectionExpr(
1056 Context, KeyLoc, ControllingExpr,
1057 Types, Exprs, NumAssocs, DefaultLoc,
1058 RParenLoc, ContainsUnexpandedParameterPack,
1059 ResultIndex));
1060}
1061
Steve Narofff69936d2007-09-16 03:34:24 +00001062/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001063/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1064/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1065/// multiple tokens. However, the common case is that StringToks points to one
1066/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001067///
John McCall60d7b3a2010-08-24 06:29:42 +00001068ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +00001069Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001070 assert(NumStringToks && "Must have at least one string!");
1071
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001072 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001073 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001074 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001075
Chris Lattner5f9e2722011-07-23 10:55:15 +00001076 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001077 for (unsigned i = 0; i != NumStringToks; ++i)
1078 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001079
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001080 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001081 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001082 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001083 else if (Literal.isUTF16())
1084 StrTy = Context.Char16Ty;
1085 else if (Literal.isUTF32())
1086 StrTy = Context.Char32Ty;
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001087 else if (Literal.Pascal)
1088 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001089
Douglas Gregor5cee1192011-07-27 05:40:30 +00001090 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1091 if (Literal.isWide())
1092 Kind = StringLiteral::Wide;
1093 else if (Literal.isUTF8())
1094 Kind = StringLiteral::UTF8;
1095 else if (Literal.isUTF16())
1096 Kind = StringLiteral::UTF16;
1097 else if (Literal.isUTF32())
1098 Kind = StringLiteral::UTF32;
1099
Douglas Gregor77a52232008-09-12 00:47:35 +00001100 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +00001101 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001102 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001103
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001104 // Get an array type for the string, according to C99 6.4.5. This includes
1105 // the nul terminator character as well as the string length for pascal
1106 // strings.
1107 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001108 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001109 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Reid Spencer5f016e22007-07-11 17:01:13 +00001111 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +00001112 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001113 Kind, Literal.Pascal, StrTy,
Sean Hunt6cf75022010-08-30 17:47:05 +00001114 &StringTokLocs[0],
1115 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001116}
1117
John McCall469a1eb2011-02-02 13:00:07 +00001118enum CaptureResult {
1119 /// No capture is required.
1120 CR_NoCapture,
1121
1122 /// A capture is required.
1123 CR_Capture,
1124
John McCall6b5a61b2011-02-07 10:33:21 +00001125 /// A by-ref capture is required.
1126 CR_CaptureByRef,
1127
John McCall469a1eb2011-02-02 13:00:07 +00001128 /// An error occurred when trying to capture the given variable.
1129 CR_Error
1130};
1131
1132/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +00001133///
John McCall469a1eb2011-02-02 13:00:07 +00001134/// \param var - the variable referenced
1135/// \param DC - the context which we couldn't capture through
1136static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +00001137diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001138 VarDecl *var, DeclContext *DC) {
1139 switch (S.ExprEvalContexts.back().Context) {
1140 case Sema::Unevaluated:
1141 // The argument will never be evaluated, so don't complain.
1142 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +00001143
John McCall469a1eb2011-02-02 13:00:07 +00001144 case Sema::PotentiallyEvaluated:
1145 case Sema::PotentiallyEvaluatedIfUsed:
1146 break;
Chris Lattner639e2d32008-10-20 05:16:36 +00001147
John McCall469a1eb2011-02-02 13:00:07 +00001148 case Sema::PotentiallyPotentiallyEvaluated:
1149 // FIXME: delay these!
1150 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +00001151 }
Mike Stump1eb44332009-09-09 15:08:12 +00001152
John McCall469a1eb2011-02-02 13:00:07 +00001153 // Don't diagnose about capture if we're not actually in code right
1154 // now; in general, there are more appropriate places that will
1155 // diagnose this.
1156 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1157
John McCall4f38f412011-03-22 23:15:50 +00001158 // Certain madnesses can happen with parameter declarations, which
1159 // we want to ignore.
1160 if (isa<ParmVarDecl>(var)) {
1161 // - If the parameter still belongs to the translation unit, then
1162 // we're actually just using one parameter in the declaration of
1163 // the next. This is useful in e.g. VLAs.
1164 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1165 return CR_NoCapture;
1166
1167 // - This particular madness can happen in ill-formed default
1168 // arguments; claim it's okay and let downstream code handle it.
1169 if (S.CurContext == var->getDeclContext()->getParent())
1170 return CR_NoCapture;
1171 }
John McCall469a1eb2011-02-02 13:00:07 +00001172
1173 DeclarationName functionName;
1174 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1175 functionName = fn->getDeclName();
1176 // FIXME: variable from enclosing block that we couldn't capture from!
1177
1178 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1179 << var->getIdentifier() << functionName;
1180 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1181 << var->getIdentifier();
1182
1183 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001184}
1185
John McCall6b5a61b2011-02-07 10:33:21 +00001186/// There is a well-formed capture at a particular scope level;
1187/// propagate it through all the nested blocks.
Richard Trieuccd891a2011-09-09 01:45:06 +00001188static CaptureResult propagateCapture(Sema &S, unsigned ValidScopeIndex,
1189 const BlockDecl::Capture &Capture) {
1190 VarDecl *var = Capture.getVariable();
John McCall6b5a61b2011-02-07 10:33:21 +00001191
1192 // Update all the inner blocks with the capture information.
Richard Trieuccd891a2011-09-09 01:45:06 +00001193 for (unsigned i = ValidScopeIndex + 1, e = S.FunctionScopes.size();
John McCall6b5a61b2011-02-07 10:33:21 +00001194 i != e; ++i) {
1195 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1196 innerBlock->Captures.push_back(
Richard Trieuccd891a2011-09-09 01:45:06 +00001197 BlockDecl::Capture(Capture.getVariable(), Capture.isByRef(),
1198 /*nested*/ true, Capture.getCopyExpr()));
John McCall6b5a61b2011-02-07 10:33:21 +00001199 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1200 }
1201
Richard Trieuccd891a2011-09-09 01:45:06 +00001202 return Capture.isByRef() ? CR_CaptureByRef : CR_Capture;
John McCall6b5a61b2011-02-07 10:33:21 +00001203}
1204
1205/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +00001206/// given value in the current context requires a variable capture.
1207///
1208/// This also keeps the captures set in the BlockScopeInfo records
1209/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +00001210static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00001211 ValueDecl *Value) {
John McCall469a1eb2011-02-02 13:00:07 +00001212 // Only variables ever require capture.
Richard Trieuccd891a2011-09-09 01:45:06 +00001213 VarDecl *var = dyn_cast<VarDecl>(Value);
John McCall76a40212011-02-09 01:13:10 +00001214 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +00001215
1216 // Fast path: variables from the current context never require capture.
1217 DeclContext *DC = S.CurContext;
1218 if (var->getDeclContext() == DC) return CR_NoCapture;
1219
1220 // Only variables with local storage require capture.
1221 // FIXME: What about 'const' variables in C++?
1222 if (!var->hasLocalStorage()) return CR_NoCapture;
1223
1224 // Otherwise, we need to capture.
1225
1226 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +00001227 do {
1228 // Only blocks (and eventually C++0x closures) can capture; other
1229 // scopes don't work.
1230 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +00001231 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +00001232
1233 BlockScopeInfo *blockScope =
1234 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1235 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1236
John McCall6b5a61b2011-02-07 10:33:21 +00001237 // Check whether we've already captured it in this block. If so,
1238 // we're done.
1239 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1240 return propagateCapture(S, functionScopesIndex,
1241 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +00001242
1243 functionScopesIndex--;
1244 DC = cast<BlockDecl>(DC)->getDeclContext();
1245 } while (var->getDeclContext() != DC);
1246
John McCall6b5a61b2011-02-07 10:33:21 +00001247 // Okay, we descended all the way to the block that defines the variable.
1248 // Actually try to capture it.
1249 QualType type = var->getType();
1250
1251 // Prohibit variably-modified types.
1252 if (type->isVariablyModifiedType()) {
1253 S.Diag(loc, diag::err_ref_vm_type);
1254 S.Diag(var->getLocation(), diag::note_declared_at);
1255 return CR_Error;
1256 }
1257
1258 // Prohibit arrays, even in __block variables, but not references to
1259 // them.
1260 if (type->isArrayType()) {
1261 S.Diag(loc, diag::err_ref_array_type);
1262 S.Diag(var->getLocation(), diag::note_declared_at);
1263 return CR_Error;
1264 }
1265
1266 S.MarkDeclarationReferenced(loc, var);
1267
1268 // The BlocksAttr indicates the variable is bound by-reference.
1269 bool byRef = var->hasAttr<BlocksAttr>();
1270
1271 // Build a copy expression.
1272 Expr *copyExpr = 0;
John McCall642a75f2011-04-28 02:15:35 +00001273 const RecordType *rtype;
1274 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1275 (rtype = type->getAs<RecordType>())) {
1276
1277 // The capture logic needs the destructor, so make sure we mark it.
1278 // Usually this is unnecessary because most local variables have
1279 // their destructors marked at declaration time, but parameters are
1280 // an exception because it's technically only the call site that
1281 // actually requires the destructor.
1282 if (isa<ParmVarDecl>(var))
1283 S.FinalizeVarWithDestructor(var, rtype);
1284
John McCall6b5a61b2011-02-07 10:33:21 +00001285 // According to the blocks spec, the capture of a variable from
1286 // the stack requires a const copy constructor. This is not true
1287 // of the copy/move done to move a __block variable to the heap.
1288 type.addConst();
1289
1290 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1291 ExprResult result =
1292 S.PerformCopyInitialization(
1293 InitializedEntity::InitializeBlock(var->getLocation(),
1294 type, false),
1295 loc, S.Owned(declRef));
1296
1297 // Build a full-expression copy expression if initialization
1298 // succeeded and used a non-trivial constructor. Recover from
1299 // errors by pretending that the copy isn't necessary.
1300 if (!result.isInvalid() &&
1301 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1302 result = S.MaybeCreateExprWithCleanups(result);
1303 copyExpr = result.take();
1304 }
1305 }
1306
1307 // We're currently at the declarer; go back to the closure.
1308 functionScopesIndex++;
1309 BlockScopeInfo *blockScope =
1310 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1311
1312 // Build a valid capture in this scope.
1313 blockScope->Captures.push_back(
1314 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1315 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1316
1317 // Propagate that to inner captures if necessary.
1318 return propagateCapture(S, functionScopesIndex,
1319 blockScope->Captures.back());
1320}
1321
Richard Trieuccd891a2011-09-09 01:45:06 +00001322static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD,
John McCall6b5a61b2011-02-07 10:33:21 +00001323 const DeclarationNameInfo &NameInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00001324 bool ByRef) {
1325 assert(isa<VarDecl>(VD) && "capturing non-variable");
John McCall6b5a61b2011-02-07 10:33:21 +00001326
Richard Trieuccd891a2011-09-09 01:45:06 +00001327 VarDecl *var = cast<VarDecl>(VD);
John McCall6b5a61b2011-02-07 10:33:21 +00001328 assert(var->hasLocalStorage() && "capturing non-local");
Richard Trieuccd891a2011-09-09 01:45:06 +00001329 assert(ByRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
John McCall6b5a61b2011-02-07 10:33:21 +00001330
1331 QualType exprType = var->getType().getNonReferenceType();
1332
1333 BlockDeclRefExpr *BDRE;
Richard Trieuccd891a2011-09-09 01:45:06 +00001334 if (!ByRef) {
John McCall6b5a61b2011-02-07 10:33:21 +00001335 // The variable will be bound by copy; make it const within the
1336 // closure, but record that this was done in the expression.
1337 bool constAdded = !exprType.isConstQualified();
1338 exprType.addConst();
1339
1340 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1341 NameInfo.getLoc(), false,
1342 constAdded);
1343 } else {
1344 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1345 NameInfo.getLoc(), true);
1346 }
1347
1348 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +00001349}
Chris Lattner639e2d32008-10-20 05:16:36 +00001350
John McCall60d7b3a2010-08-24 06:29:42 +00001351ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001352Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001353 SourceLocation Loc,
1354 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001355 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001356 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001357}
1358
John McCall76a40212011-02-09 01:13:10 +00001359/// BuildDeclRefExpr - Build an expression that references a
1360/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001361ExprResult
John McCall76a40212011-02-09 01:13:10 +00001362Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001363 const DeclarationNameInfo &NameInfo,
1364 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001365 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +00001366
John McCall7eb0a9e2010-11-24 05:12:34 +00001367 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00001368 SS? SS->getWithLocInContext(Context)
1369 : NestedNameSpecifierLoc(),
John McCall7eb0a9e2010-11-24 05:12:34 +00001370 D, NameInfo, Ty, VK);
1371
1372 // Just in case we're building an illegal pointer-to-member.
1373 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1374 E->setObjectKind(OK_BitField);
1375
1376 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001377}
1378
Abramo Bagnara25777432010-08-11 22:01:17 +00001379/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001380/// possibly a list of template arguments.
1381///
1382/// If this produces template arguments, it is permitted to call
1383/// DecomposeTemplateName.
1384///
1385/// This actually loses a lot of source location information for
1386/// non-standard name kinds; we should consider preserving that in
1387/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001388void
1389Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1390 TemplateArgumentListInfo &Buffer,
1391 DeclarationNameInfo &NameInfo,
1392 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001393 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1394 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1395 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1396
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001397 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall129e2df2009-11-30 22:42:35 +00001398 Id.TemplateId->getTemplateArgs(),
1399 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001400 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001401 TemplateArgsPtr.release();
1402
John McCall2b5289b2010-08-23 07:28:44 +00001403 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001404 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001405 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001406 TemplateArgs = &Buffer;
1407 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001408 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001409 TemplateArgs = 0;
1410 }
1411}
1412
John McCall578b69b2009-12-16 08:11:27 +00001413/// Diagnose an empty lookup.
1414///
1415/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001416bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001417 CorrectTypoContext CTC,
1418 TemplateArgumentListInfo *ExplicitTemplateArgs,
1419 Expr **Args, unsigned NumArgs) {
John McCall578b69b2009-12-16 08:11:27 +00001420 DeclarationName Name = R.getLookupName();
1421
John McCall578b69b2009-12-16 08:11:27 +00001422 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001423 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001424 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1425 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001426 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001427 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001428 diagnostic_suggest = diag::err_undeclared_use_suggest;
1429 }
John McCall578b69b2009-12-16 08:11:27 +00001430
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001431 // If the original lookup was an unqualified lookup, fake an
1432 // unqualified lookup. This is useful when (for example) the
1433 // original lookup would not have found something because it was a
1434 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001435 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001436 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001437 if (isa<CXXRecordDecl>(DC)) {
1438 LookupQualifiedName(R, DC);
1439
1440 if (!R.empty()) {
1441 // Don't give errors about ambiguities in this lookup.
1442 R.suppressDiagnostics();
1443
1444 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1445 bool isInstance = CurMethod &&
1446 CurMethod->isInstance() &&
1447 DC == CurMethod->getParent();
1448
1449 // Give a code modification hint to insert 'this->'.
1450 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1451 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001452 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001453 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1454 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001455 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001456 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001457 if (DepMethod) {
Francois Pichet0f74d1e2011-09-07 00:14:57 +00001458 if (getLangOptions().Microsoft)
1459 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001460 Diag(R.getNameLoc(), diagnostic) << Name
1461 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1462 QualType DepThisType = DepMethod->getThisType(Context);
1463 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1464 R.getNameLoc(), DepThisType, false);
1465 TemplateArgumentListInfo TList;
1466 if (ULE->hasExplicitTemplateArgs())
1467 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001468
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001469 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00001470 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001471 CXXDependentScopeMemberExpr *DepExpr =
1472 CXXDependentScopeMemberExpr::Create(
1473 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001474 SS.getWithLocInContext(Context), NULL,
Francois Pichetf7400122011-09-04 23:00:48 +00001475 R.getLookupNameInfo(),
1476 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001477 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001478 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001479 // FIXME: we should be able to handle this case too. It is correct
1480 // to add this-> here. This is a workaround for PR7947.
1481 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001482 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001483 } else {
John McCall578b69b2009-12-16 08:11:27 +00001484 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001485 }
John McCall578b69b2009-12-16 08:11:27 +00001486
1487 // Do we really want to note all of these?
1488 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1489 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1490
1491 // Tell the callee to try to recover.
1492 return false;
1493 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001494
1495 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001496 }
1497 }
1498
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001499 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001500 TypoCorrection Corrected;
1501 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1502 S, &SS, NULL, false, CTC))) {
1503 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1504 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1505 R.setLookupName(Corrected.getCorrection());
1506
Hans Wennborg701d1e72011-07-12 08:45:31 +00001507 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001508 if (Corrected.isOverloaded()) {
1509 OverloadCandidateSet OCS(R.getNameLoc());
1510 OverloadCandidateSet::iterator Best;
1511 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1512 CDEnd = Corrected.end();
1513 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001514 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001515 dyn_cast<FunctionTemplateDecl>(*CD))
1516 AddTemplateOverloadCandidate(
1517 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1518 Args, NumArgs, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001519 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1520 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1521 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1522 Args, NumArgs, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001523 }
1524 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1525 case OR_Success:
1526 ND = Best->Function;
1527 break;
1528 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001529 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001530 }
1531 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001532 R.addDecl(ND);
1533 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001534 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001535 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1536 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001537 else
1538 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001539 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001540 << SS.getRange()
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001541 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1542 if (ND)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001543 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001544 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001545
1546 // Tell the callee to try to recover.
1547 return false;
1548 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001549
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001550 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001551 // FIXME: If we ended up with a typo for a type name or
1552 // Objective-C class name, we're in trouble because the parser
1553 // is in the wrong place to recover. Suggest the typo
1554 // correction, but don't make it a fix-it since we're not going
1555 // to recover well anyway.
1556 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001557 Diag(R.getNameLoc(), diagnostic_suggest)
1558 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001559 else
1560 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001561 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001562 << SS.getRange();
1563
1564 // Don't try to recover; it won't work.
1565 return true;
1566 }
1567 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001568 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001569 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001570 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001571 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001572 else
Douglas Gregord203a162010-01-01 00:15:04 +00001573 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001574 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001575 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001576 return true;
1577 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001578 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001579 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001580
1581 // Emit a special diagnostic for failed member lookups.
1582 // FIXME: computing the declaration context might fail here (?)
1583 if (!SS.isEmpty()) {
1584 Diag(R.getNameLoc(), diag::err_no_member)
1585 << Name << computeDeclContext(SS, false)
1586 << SS.getRange();
1587 return true;
1588 }
1589
John McCall578b69b2009-12-16 08:11:27 +00001590 // Give up, we can't recover.
1591 Diag(R.getNameLoc(), diagnostic) << Name;
1592 return true;
1593}
1594
John McCall60d7b3a2010-08-24 06:29:42 +00001595ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001596 CXXScopeSpec &SS,
1597 UnqualifiedId &Id,
1598 bool HasTrailingLParen,
Richard Trieuccd891a2011-09-09 01:45:06 +00001599 bool IsAddressOfOperand) {
1600 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCallf7a1a742009-11-24 19:00:30 +00001601 "cannot be direct & operand and have a trailing lparen");
1602
1603 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001604 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001605
John McCall129e2df2009-11-30 22:42:35 +00001606 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001607
1608 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001609 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001610 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001611 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001612
Abramo Bagnara25777432010-08-11 22:01:17 +00001613 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001614 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001615 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001616
John McCallf7a1a742009-11-24 19:00:30 +00001617 // C++ [temp.dep.expr]p3:
1618 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001619 // -- an identifier that was declared with a dependent type,
1620 // (note: handled after lookup)
1621 // -- a template-id that is dependent,
1622 // (note: handled in BuildTemplateIdExpr)
1623 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001624 // -- a nested-name-specifier that contains a class-name that
1625 // names a dependent type.
1626 // Determine whether this is a member of an unknown specialization;
1627 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001628 bool DependentID = false;
1629 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1630 Name.getCXXNameType()->isDependentType()) {
1631 DependentID = true;
1632 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001633 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001634 if (RequireCompleteDeclContext(SS, DC))
1635 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001636 } else {
1637 DependentID = true;
1638 }
1639 }
1640
Chris Lattner337e5502011-02-18 01:27:55 +00001641 if (DependentID)
Richard Trieuccd891a2011-09-09 01:45:06 +00001642 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001643 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001644
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001645 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001646 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001647 LookupResult R(*this, NameInfo,
1648 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1649 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001650 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001651 // Lookup the template name again to correctly establish the context in
1652 // which it was found. This is really unfortunate as we already did the
1653 // lookup to determine that it was a template name in the first place. If
1654 // this becomes a performance hit, we can work harder to preserve those
1655 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001656 bool MemberOfUnknownSpecialization;
1657 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1658 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001659
1660 if (MemberOfUnknownSpecialization ||
1661 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Richard Trieuccd891a2011-09-09 01:45:06 +00001662 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001663 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001664 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001665 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001666 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001668 // If the result might be in a dependent base class, this is a dependent
1669 // id-expression.
1670 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Richard Trieuccd891a2011-09-09 01:45:06 +00001671 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001672 TemplateArgs);
1673
John McCallf7a1a742009-11-24 19:00:30 +00001674 // If this reference is in an Objective-C method, then we need to do
1675 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001676 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001677 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001678 if (E.isInvalid())
1679 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001680
Chris Lattner337e5502011-02-18 01:27:55 +00001681 if (Expr *Ex = E.takeAs<Expr>())
1682 return Owned(Ex);
1683
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001684 // for further use, this must be set to false if in class method.
1685 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001686 }
Chris Lattner8a934232008-03-31 00:36:02 +00001687 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001688
John McCallf7a1a742009-11-24 19:00:30 +00001689 if (R.isAmbiguous())
1690 return ExprError();
1691
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001692 // Determine whether this name might be a candidate for
1693 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001694 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001695
John McCallf7a1a742009-11-24 19:00:30 +00001696 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001697 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001698 // in C90, extension in C99, forbidden in C++).
1699 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1700 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1701 if (D) R.addDecl(D);
1702 }
1703
1704 // If this name wasn't predeclared and if this is not a function
1705 // call, diagnose the problem.
1706 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001707 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001708 return ExprError();
1709
1710 assert(!R.empty() &&
1711 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001712
1713 // If we found an Objective-C instance variable, let
1714 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001715 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001716 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1717 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001718 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001719 assert(E.isInvalid() || E.get());
1720 return move(E);
1721 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001722 }
1723 }
Mike Stump1eb44332009-09-09 15:08:12 +00001724
John McCallf7a1a742009-11-24 19:00:30 +00001725 // This is guaranteed from this point on.
1726 assert(!R.empty() || ADL);
1727
John McCallaa81e162009-12-01 22:10:20 +00001728 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001729 // C++ [class.mfct.non-static]p3:
1730 // When an id-expression that is not part of a class member access
1731 // syntax and not used to form a pointer to member is used in the
1732 // body of a non-static member function of class X, if name lookup
1733 // resolves the name in the id-expression to a non-static non-type
1734 // member of some class C, the id-expression is transformed into a
1735 // class member access expression using (*this) as the
1736 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001737 //
1738 // But we don't actually need to do this for '&' operands if R
1739 // resolved to a function or overloaded function set, because the
1740 // expression is ill-formed if it actually works out to be a
1741 // non-static member function:
1742 //
1743 // C++ [expr.ref]p4:
1744 // Otherwise, if E1.E2 refers to a non-static member function. . .
1745 // [t]he expression can be used only as the left-hand operand of a
1746 // member function call.
1747 //
1748 // There are other safeguards against such uses, but it's important
1749 // to get this right here so that we don't end up making a
1750 // spuriously dependent expression if we're inside a dependent
1751 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001752 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001753 bool MightBeImplicitMember;
Richard Trieuccd891a2011-09-09 01:45:06 +00001754 if (!IsAddressOfOperand)
John McCall9c72c602010-08-27 09:08:28 +00001755 MightBeImplicitMember = true;
1756 else if (!SS.isEmpty())
1757 MightBeImplicitMember = false;
1758 else if (R.isOverloadedResult())
1759 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001760 else if (R.isUnresolvableResult())
1761 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001762 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001763 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1764 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001765
1766 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001767 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001768 }
1769
John McCallf7a1a742009-11-24 19:00:30 +00001770 if (TemplateArgs)
1771 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001772
John McCallf7a1a742009-11-24 19:00:30 +00001773 return BuildDeclarationNameExpr(SS, R, ADL);
1774}
1775
John McCall129e2df2009-11-30 22:42:35 +00001776/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1777/// declaration name, generally during template instantiation.
1778/// There's a large number of things which don't need to be done along
1779/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001780ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001781Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001782 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001783 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001784 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001785 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001786
John McCall77bb1aa2010-05-01 00:40:08 +00001787 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001788 return ExprError();
1789
Abramo Bagnara25777432010-08-11 22:01:17 +00001790 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001791 LookupQualifiedName(R, DC);
1792
1793 if (R.isAmbiguous())
1794 return ExprError();
1795
1796 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001797 Diag(NameInfo.getLoc(), diag::err_no_member)
1798 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001799 return ExprError();
1800 }
1801
1802 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1803}
1804
1805/// LookupInObjCMethod - The parser has read a name in, and Sema has
1806/// detected that we're currently inside an ObjC method. Perform some
1807/// additional lookup.
1808///
1809/// Ideally, most of this would be done by lookup, but there's
1810/// actually quite a lot of extra work involved.
1811///
1812/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001813ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001814Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001815 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001816 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001817 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001818
John McCallf7a1a742009-11-24 19:00:30 +00001819 // There are two cases to handle here. 1) scoped lookup could have failed,
1820 // in which case we should look for an ivar. 2) scoped lookup could have
1821 // found a decl, but that decl is outside the current instance method (i.e.
1822 // a global variable). In these two cases, we do a lookup for an ivar with
1823 // this name, if the lookup sucedes, we replace it our current decl.
1824
1825 // If we're in a class method, we don't normally want to look for
1826 // ivars. But if we don't find anything else, and there's an
1827 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001828 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001829
1830 bool LookForIvars;
1831 if (Lookup.empty())
1832 LookForIvars = true;
1833 else if (IsClassMethod)
1834 LookForIvars = false;
1835 else
1836 LookForIvars = (Lookup.isSingleResult() &&
1837 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001838 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001839 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001840 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001841 ObjCInterfaceDecl *ClassDeclared;
1842 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1843 // Diagnose using an ivar in a class method.
1844 if (IsClassMethod)
1845 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1846 << IV->getDeclName());
1847
1848 // If we're referencing an invalid decl, just return this as a silent
1849 // error node. The error diagnostic was already emitted on the decl.
1850 if (IV->isInvalidDecl())
1851 return ExprError();
1852
1853 // Check if referencing a field with __attribute__((deprecated)).
1854 if (DiagnoseUseOfDecl(IV, Loc))
1855 return ExprError();
1856
1857 // Diagnose the use of an ivar outside of the declaring class.
1858 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1859 ClassDeclared != IFace)
1860 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1861
1862 // FIXME: This should use a new expr for a direct reference, don't
1863 // turn this into Self->ivar, just return a BareIVarExpr or something.
1864 IdentifierInfo &II = Context.Idents.get("self");
1865 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001866 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001867 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00001868 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00001869 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001870 SelfName, false, false);
1871 if (SelfExpr.isInvalid())
1872 return ExprError();
1873
John Wiegley429bb272011-04-08 18:41:53 +00001874 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1875 if (SelfExpr.isInvalid())
1876 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001877
John McCallf7a1a742009-11-24 19:00:30 +00001878 MarkDeclarationReferenced(Loc, IV);
1879 return Owned(new (Context)
1880 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00001881 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001882 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001883 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001884 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001885 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001886 ObjCInterfaceDecl *ClassDeclared;
1887 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1888 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1889 IFace == ClassDeclared)
1890 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1891 }
1892 }
1893
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001894 if (Lookup.empty() && II && AllowBuiltinCreation) {
1895 // FIXME. Consolidate this with similar code in LookupName.
1896 if (unsigned BuiltinID = II->getBuiltinID()) {
1897 if (!(getLangOptions().CPlusPlus &&
1898 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1899 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1900 S, Lookup.isForRedeclaration(),
1901 Lookup.getNameLoc());
1902 if (D) Lookup.addDecl(D);
1903 }
1904 }
1905 }
John McCallf7a1a742009-11-24 19:00:30 +00001906 // Sentinel value saying that we didn't do anything special.
1907 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001908}
John McCallba135432009-11-21 08:51:07 +00001909
John McCall6bb80172010-03-30 21:47:33 +00001910/// \brief Cast a base object to a member's actual type.
1911///
1912/// Logically this happens in three phases:
1913///
1914/// * First we cast from the base type to the naming class.
1915/// The naming class is the class into which we were looking
1916/// when we found the member; it's the qualifier type if a
1917/// qualifier was provided, and otherwise it's the base type.
1918///
1919/// * Next we cast from the naming class to the declaring class.
1920/// If the member we found was brought into a class's scope by
1921/// a using declaration, this is that class; otherwise it's
1922/// the class declaring the member.
1923///
1924/// * Finally we cast from the declaring class to the "true"
1925/// declaring class of the member. This conversion does not
1926/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00001927ExprResult
1928Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001929 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001930 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001931 NamedDecl *Member) {
1932 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1933 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00001934 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001935
Douglas Gregor5fccd362010-03-03 23:55:11 +00001936 QualType DestRecordType;
1937 QualType DestType;
1938 QualType FromRecordType;
1939 QualType FromType = From->getType();
1940 bool PointerConversions = false;
1941 if (isa<FieldDecl>(Member)) {
1942 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001943
Douglas Gregor5fccd362010-03-03 23:55:11 +00001944 if (FromType->getAs<PointerType>()) {
1945 DestType = Context.getPointerType(DestRecordType);
1946 FromRecordType = FromType->getPointeeType();
1947 PointerConversions = true;
1948 } else {
1949 DestType = DestRecordType;
1950 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001951 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001952 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1953 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00001954 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001955
Douglas Gregor5fccd362010-03-03 23:55:11 +00001956 DestType = Method->getThisType(Context);
1957 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001958
Douglas Gregor5fccd362010-03-03 23:55:11 +00001959 if (FromType->getAs<PointerType>()) {
1960 FromRecordType = FromType->getPointeeType();
1961 PointerConversions = true;
1962 } else {
1963 FromRecordType = FromType;
1964 DestType = DestRecordType;
1965 }
1966 } else {
1967 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00001968 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00001969 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001970
Douglas Gregor5fccd362010-03-03 23:55:11 +00001971 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00001972 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001973
Douglas Gregor5fccd362010-03-03 23:55:11 +00001974 // If the unqualified types are the same, no conversion is necessary.
1975 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00001976 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001977
John McCall6bb80172010-03-30 21:47:33 +00001978 SourceRange FromRange = From->getSourceRange();
1979 SourceLocation FromLoc = FromRange.getBegin();
1980
John McCall5baba9d2010-08-25 10:28:54 +00001981 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00001982
Douglas Gregor5fccd362010-03-03 23:55:11 +00001983 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001984 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00001985 // class name.
1986 //
1987 // If the member was a qualified name and the qualified referred to a
1988 // specific base subobject type, we'll cast to that intermediate type
1989 // first and then to the object in which the member is declared. That allows
1990 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1991 //
1992 // class Base { public: int x; };
1993 // class Derived1 : public Base { };
1994 // class Derived2 : public Base { };
1995 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1996 //
1997 // void VeryDerived::f() {
1998 // x = 17; // error: ambiguous base subobjects
1999 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2000 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002001 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002002 QualType QType = QualType(Qualifier->getAsType(), 0);
2003 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2004 assert(QType->isRecordType() && "lookup done with non-record type");
2005
2006 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2007
2008 // In C++98, the qualifier type doesn't actually have to be a base
2009 // type of the object type, in which case we just ignore it.
2010 // Otherwise build the appropriate casts.
2011 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002012 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002013 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002014 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002015 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002016
Douglas Gregor5fccd362010-03-03 23:55:11 +00002017 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002018 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002019 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2020 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002021
2022 FromType = QType;
2023 FromRecordType = QRecordType;
2024
2025 // If the qualifier type was the same as the destination type,
2026 // we're done.
2027 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002028 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002029 }
2030 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002031
John McCall6bb80172010-03-30 21:47:33 +00002032 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002033
John McCall6bb80172010-03-30 21:47:33 +00002034 // If we actually found the member through a using declaration, cast
2035 // down to the using declaration's type.
2036 //
2037 // Pointer equality is fine here because only one declaration of a
2038 // class ever has member declarations.
2039 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2040 assert(isa<UsingShadowDecl>(FoundDecl));
2041 QualType URecordType = Context.getTypeDeclType(
2042 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2043
2044 // We only need to do this if the naming-class to declaring-class
2045 // conversion is non-trivial.
2046 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2047 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002048 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002049 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002050 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002051 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002052
John McCall6bb80172010-03-30 21:47:33 +00002053 QualType UType = URecordType;
2054 if (PointerConversions)
2055 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002056 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2057 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002058 FromType = UType;
2059 FromRecordType = URecordType;
2060 }
2061
2062 // We don't do access control for the conversion from the
2063 // declaring class to the true declaring class.
2064 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002065 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002066
John McCallf871d0c2010-08-07 06:22:56 +00002067 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002068 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2069 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002070 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002071 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002072
John Wiegley429bb272011-04-08 18:41:53 +00002073 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2074 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002075}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002076
John McCallf7a1a742009-11-24 19:00:30 +00002077bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002078 const LookupResult &R,
2079 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002080 // Only when used directly as the postfix-expression of a call.
2081 if (!HasTrailingLParen)
2082 return false;
2083
2084 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002085 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002086 return false;
2087
2088 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002089 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002090 return false;
2091
2092 // Turn off ADL when we find certain kinds of declarations during
2093 // normal lookup:
2094 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2095 NamedDecl *D = *I;
2096
2097 // C++0x [basic.lookup.argdep]p3:
2098 // -- a declaration of a class member
2099 // Since using decls preserve this property, we check this on the
2100 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002101 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002102 return false;
2103
2104 // C++0x [basic.lookup.argdep]p3:
2105 // -- a block-scope function declaration that is not a
2106 // using-declaration
2107 // NOTE: we also trigger this for function templates (in fact, we
2108 // don't check the decl type at all, since all other decl types
2109 // turn off ADL anyway).
2110 if (isa<UsingShadowDecl>(D))
2111 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2112 else if (D->getDeclContext()->isFunctionOrMethod())
2113 return false;
2114
2115 // C++0x [basic.lookup.argdep]p3:
2116 // -- a declaration that is neither a function or a function
2117 // template
2118 // And also for builtin functions.
2119 if (isa<FunctionDecl>(D)) {
2120 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2121
2122 // But also builtin functions.
2123 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2124 return false;
2125 } else if (!isa<FunctionTemplateDecl>(D))
2126 return false;
2127 }
2128
2129 return true;
2130}
2131
2132
John McCallba135432009-11-21 08:51:07 +00002133/// Diagnoses obvious problems with the use of the given declaration
2134/// as an expression. This is only actually called for lookups that
2135/// were not overloaded, and it doesn't promise that the declaration
2136/// will in fact be used.
2137static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002138 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002139 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2140 return true;
2141 }
2142
2143 if (isa<ObjCInterfaceDecl>(D)) {
2144 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2145 return true;
2146 }
2147
2148 if (isa<NamespaceDecl>(D)) {
2149 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2150 return true;
2151 }
2152
2153 return false;
2154}
2155
John McCall60d7b3a2010-08-24 06:29:42 +00002156ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002157Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002158 LookupResult &R,
2159 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002160 // If this is a single, fully-resolved result and we don't need ADL,
2161 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002162 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002163 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2164 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002165
2166 // We only need to check the declaration if there's exactly one
2167 // result, because in the overloaded case the results can only be
2168 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002169 if (R.isSingleResult() &&
2170 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002171 return ExprError();
2172
John McCallc373d482010-01-27 01:50:18 +00002173 // Otherwise, just build an unresolved lookup expression. Suppress
2174 // any lookup-related diagnostics; we'll hash these out later, when
2175 // we've picked a target.
2176 R.suppressDiagnostics();
2177
John McCallba135432009-11-21 08:51:07 +00002178 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002179 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002180 SS.getWithLocInContext(Context),
2181 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002182 NeedsADL, R.isOverloadedResult(),
2183 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002184
2185 return Owned(ULE);
2186}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002187
John McCallba135432009-11-21 08:51:07 +00002188/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002189ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002190Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002191 const DeclarationNameInfo &NameInfo,
2192 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002193 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002194 assert(!isa<FunctionTemplateDecl>(D) &&
2195 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002196
Abramo Bagnara25777432010-08-11 22:01:17 +00002197 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002198 if (CheckDeclInExpr(*this, Loc, D))
2199 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002200
Douglas Gregor9af2f522009-12-01 16:58:18 +00002201 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2202 // Specifically diagnose references to class templates that are missing
2203 // a template argument list.
2204 Diag(Loc, diag::err_template_decl_ref)
2205 << Template << SS.getRange();
2206 Diag(Template->getLocation(), diag::note_template_decl_here);
2207 return ExprError();
2208 }
2209
2210 // Make sure that we're referring to a value.
2211 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2212 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002213 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002214 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002215 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002216 return ExprError();
2217 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002218
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002219 // Check whether this declaration can be used. Note that we suppress
2220 // this check when we're going to perform argument-dependent lookup
2221 // on this function name, because this might not be the function
2222 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002223 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002224 return ExprError();
2225
Steve Naroffdd972f22008-09-05 22:11:13 +00002226 // Only create DeclRefExpr's for valid Decl's.
2227 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002228 return ExprError();
2229
John McCall5808ce42011-02-03 08:15:49 +00002230 // Handle members of anonymous structs and unions. If we got here,
2231 // and the reference is to a class member indirect field, then this
2232 // must be the subject of a pointer-to-member expression.
2233 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2234 if (!indirectField->isCXXClassMember())
2235 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2236 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002237
Chris Lattner639e2d32008-10-20 05:16:36 +00002238 // If the identifier reference is inside a block, and it refers to a value
2239 // that is outside the block, create a BlockDeclRefExpr instead of a
2240 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2241 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002242 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002243 // We do not do this for things like enum constants, global variables, etc,
2244 // as they do not get snapshotted.
2245 //
John McCall6b5a61b2011-02-07 10:33:21 +00002246 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002247 case CR_Error:
2248 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002249
John McCall469a1eb2011-02-02 13:00:07 +00002250 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002251 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2252 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2253
2254 case CR_CaptureByRef:
2255 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2256 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002257
2258 case CR_NoCapture: {
2259 // If this reference is not in a block or if the referenced
2260 // variable is within the block, create a normal DeclRefExpr.
2261
2262 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002263 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002264
2265 switch (D->getKind()) {
2266 // Ignore all the non-ValueDecl kinds.
2267#define ABSTRACT_DECL(kind)
2268#define VALUE(type, base)
2269#define DECL(type, base) \
2270 case Decl::type:
2271#include "clang/AST/DeclNodes.inc"
2272 llvm_unreachable("invalid value decl kind");
2273 return ExprError();
2274
2275 // These shouldn't make it here.
2276 case Decl::ObjCAtDefsField:
2277 case Decl::ObjCIvar:
2278 llvm_unreachable("forming non-member reference to ivar?");
2279 return ExprError();
2280
2281 // Enum constants are always r-values and never references.
2282 // Unresolved using declarations are dependent.
2283 case Decl::EnumConstant:
2284 case Decl::UnresolvedUsingValue:
2285 valueKind = VK_RValue;
2286 break;
2287
2288 // Fields and indirect fields that got here must be for
2289 // pointer-to-member expressions; we just call them l-values for
2290 // internal consistency, because this subexpression doesn't really
2291 // exist in the high-level semantics.
2292 case Decl::Field:
2293 case Decl::IndirectField:
2294 assert(getLangOptions().CPlusPlus &&
2295 "building reference to field in C?");
2296
2297 // These can't have reference type in well-formed programs, but
2298 // for internal consistency we do this anyway.
2299 type = type.getNonReferenceType();
2300 valueKind = VK_LValue;
2301 break;
2302
2303 // Non-type template parameters are either l-values or r-values
2304 // depending on the type.
2305 case Decl::NonTypeTemplateParm: {
2306 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2307 type = reftype->getPointeeType();
2308 valueKind = VK_LValue; // even if the parameter is an r-value reference
2309 break;
2310 }
2311
2312 // For non-references, we need to strip qualifiers just in case
2313 // the template parameter was declared as 'const int' or whatever.
2314 valueKind = VK_RValue;
2315 type = type.getUnqualifiedType();
2316 break;
2317 }
2318
2319 case Decl::Var:
2320 // In C, "extern void blah;" is valid and is an r-value.
2321 if (!getLangOptions().CPlusPlus &&
2322 !type.hasQualifiers() &&
2323 type->isVoidType()) {
2324 valueKind = VK_RValue;
2325 break;
2326 }
2327 // fallthrough
2328
2329 case Decl::ImplicitParam:
2330 case Decl::ParmVar:
2331 // These are always l-values.
2332 valueKind = VK_LValue;
2333 type = type.getNonReferenceType();
2334 break;
2335
2336 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002337 const FunctionType *fty = type->castAs<FunctionType>();
2338
2339 // If we're referring to a function with an __unknown_anytype
2340 // result type, make the entire expression __unknown_anytype.
2341 if (fty->getResultType() == Context.UnknownAnyTy) {
2342 type = Context.UnknownAnyTy;
2343 valueKind = VK_RValue;
2344 break;
2345 }
2346
John McCall76a40212011-02-09 01:13:10 +00002347 // Functions are l-values in C++.
2348 if (getLangOptions().CPlusPlus) {
2349 valueKind = VK_LValue;
2350 break;
2351 }
2352
2353 // C99 DR 316 says that, if a function type comes from a
2354 // function definition (without a prototype), that type is only
2355 // used for checking compatibility. Therefore, when referencing
2356 // the function, we pretend that we don't have the full function
2357 // type.
John McCall755d8492011-04-12 00:42:48 +00002358 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2359 isa<FunctionProtoType>(fty))
2360 type = Context.getFunctionNoProtoType(fty->getResultType(),
2361 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002362
2363 // Functions are r-values in C.
2364 valueKind = VK_RValue;
2365 break;
2366 }
2367
2368 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002369 // If we're referring to a method with an __unknown_anytype
2370 // result type, make the entire expression __unknown_anytype.
2371 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002372 if (const FunctionProtoType *proto
2373 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002374 if (proto->getResultType() == Context.UnknownAnyTy) {
2375 type = Context.UnknownAnyTy;
2376 valueKind = VK_RValue;
2377 break;
2378 }
2379
John McCall76a40212011-02-09 01:13:10 +00002380 // C++ methods are l-values if static, r-values if non-static.
2381 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2382 valueKind = VK_LValue;
2383 break;
2384 }
2385 // fallthrough
2386
2387 case Decl::CXXConversion:
2388 case Decl::CXXDestructor:
2389 case Decl::CXXConstructor:
2390 valueKind = VK_RValue;
2391 break;
2392 }
2393
2394 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2395 }
2396
John McCall469a1eb2011-02-02 13:00:07 +00002397 }
John McCallf89e55a2010-11-18 06:31:45 +00002398
John McCall6b5a61b2011-02-07 10:33:21 +00002399 llvm_unreachable("unknown capture result");
2400 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002401}
2402
John McCall755d8492011-04-12 00:42:48 +00002403ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002404 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002405
Reid Spencer5f016e22007-07-11 17:01:13 +00002406 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002407 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002408 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2409 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2410 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002411 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002412
Chris Lattnerfa28b302008-01-12 08:14:25 +00002413 // Pre-defined identifiers are of type char[x], where x is the length of the
2414 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002415
Anders Carlsson3a082d82009-09-08 18:24:21 +00002416 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002417 if (!currentDecl && getCurBlock())
2418 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002419 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002420 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002421 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002422 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002423
Anders Carlsson773f3972009-09-11 01:22:35 +00002424 QualType ResTy;
2425 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2426 ResTy = Context.DependentTy;
2427 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002428 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002429
Anders Carlsson773f3972009-09-11 01:22:35 +00002430 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002431 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002432 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2433 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002434 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002435}
2436
John McCall60d7b3a2010-08-24 06:29:42 +00002437ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002438 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002439 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002440 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002441 if (Invalid)
2442 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002443
Benjamin Kramerddeea562010-02-27 13:44:12 +00002444 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002445 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002446 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002447 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002448
Chris Lattnere8337df2009-12-30 21:19:39 +00002449 QualType Ty;
2450 if (!getLangOptions().CPlusPlus)
2451 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2452 else if (Literal.isWide())
2453 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002454 else if (Literal.isUTF16())
2455 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2456 else if (Literal.isUTF32())
2457 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002458 else if (Literal.isMultiChar())
2459 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002460 else
2461 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002462
Douglas Gregor5cee1192011-07-27 05:40:30 +00002463 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2464 if (Literal.isWide())
2465 Kind = CharacterLiteral::Wide;
2466 else if (Literal.isUTF16())
2467 Kind = CharacterLiteral::UTF16;
2468 else if (Literal.isUTF32())
2469 Kind = CharacterLiteral::UTF32;
2470
2471 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2472 Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002473}
2474
John McCall60d7b3a2010-08-24 06:29:42 +00002475ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002476 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002477 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2478 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002479 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002480 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002481 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002482 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002483 }
Ted Kremenek28396602009-01-13 23:19:12 +00002484
Reid Spencer5f016e22007-07-11 17:01:13 +00002485 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002486 // Add padding so that NumericLiteralParser can overread by one character.
2487 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002488 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002489
Reid Spencer5f016e22007-07-11 17:01:13 +00002490 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002491 bool Invalid = false;
2492 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2493 if (Invalid)
2494 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002495
Mike Stump1eb44332009-09-09 15:08:12 +00002496 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002497 Tok.getLocation(), PP);
2498 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002499 return ExprError();
2500
Chris Lattner5d661452007-08-26 03:42:43 +00002501 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002502
Chris Lattner5d661452007-08-26 03:42:43 +00002503 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002504 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002505 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002506 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002507 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002508 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002509 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002510 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002511
2512 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2513
John McCall94c939d2009-12-24 09:08:04 +00002514 using llvm::APFloat;
2515 APFloat Val(Format);
2516
2517 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002518
2519 // Overflow is always an error, but underflow is only an error if
2520 // we underflowed to zero (APFloat reports denormals as underflow).
2521 if ((result & APFloat::opOverflow) ||
2522 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002523 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002524 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002525 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002526 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002527 APFloat::getLargest(Format).toString(buffer);
2528 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002529 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002530 APFloat::getSmallest(Format).toString(buffer);
2531 }
2532
2533 Diag(Tok.getLocation(), diagnostic)
2534 << Ty
Chris Lattner5f9e2722011-07-23 10:55:15 +00002535 << StringRef(buffer.data(), buffer.size());
John McCall94c939d2009-12-24 09:08:04 +00002536 }
2537
2538 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002539 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002540
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002541 if (Ty == Context.DoubleTy) {
2542 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002543 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002544 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2545 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002546 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002547 }
2548 }
Chris Lattner5d661452007-08-26 03:42:43 +00002549 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002550 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002551 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002552 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002553
Neil Boothb9449512007-08-29 22:00:19 +00002554 // long long is a C99 feature.
2555 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002556 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002557 Diag(Tok.getLocation(), diag::ext_longlong);
2558
Reid Spencer5f016e22007-07-11 17:01:13 +00002559 // Get the value in the widest-possible width.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002560 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002561
Reid Spencer5f016e22007-07-11 17:01:13 +00002562 if (Literal.GetIntegerValue(ResultVal)) {
2563 // If this value didn't fit into uintmax_t, warn and force to ull.
2564 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002565 Ty = Context.UnsignedLongLongTy;
2566 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002567 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002568 } else {
2569 // If this value fits into a ULL, try to figure out what else it fits into
2570 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002571
Reid Spencer5f016e22007-07-11 17:01:13 +00002572 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2573 // be an unsigned int.
2574 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2575
2576 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002577 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002578 if (!Literal.isLong && !Literal.isLongLong) {
2579 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002580 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002581
Reid Spencer5f016e22007-07-11 17:01:13 +00002582 // Does it fit in a unsigned int?
2583 if (ResultVal.isIntN(IntSize)) {
2584 // Does it fit in a signed int?
2585 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002586 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002587 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002588 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002589 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002590 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002591 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002592
Reid Spencer5f016e22007-07-11 17:01:13 +00002593 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002594 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002595 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002596
Reid Spencer5f016e22007-07-11 17:01:13 +00002597 // Does it fit in a unsigned long?
2598 if (ResultVal.isIntN(LongSize)) {
2599 // Does it fit in a signed long?
2600 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002601 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002602 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002603 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002604 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002605 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002606 }
2607
Reid Spencer5f016e22007-07-11 17:01:13 +00002608 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002609 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002610 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002611
Reid Spencer5f016e22007-07-11 17:01:13 +00002612 // Does it fit in a unsigned long long?
2613 if (ResultVal.isIntN(LongLongSize)) {
2614 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002615 // To be compatible with MSVC, hex integer literals ending with the
2616 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002617 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2618 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002619 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002620 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002621 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002622 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002623 }
2624 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002625
Reid Spencer5f016e22007-07-11 17:01:13 +00002626 // If we still couldn't decide a type, we probably have something that
2627 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002628 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002629 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002630 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002631 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002632 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002633
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002634 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002635 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002636 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002637 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002638 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002639
Chris Lattner5d661452007-08-26 03:42:43 +00002640 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2641 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002642 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002643 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002644
2645 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002646}
2647
Richard Trieuccd891a2011-09-09 01:45:06 +00002648ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002649 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002650 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002651}
2652
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002653static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2654 SourceLocation Loc,
2655 SourceRange ArgRange) {
2656 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2657 // scalar or vector data type argument..."
2658 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2659 // type (C99 6.2.5p18) or void.
2660 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2661 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2662 << T << ArgRange;
2663 return true;
2664 }
2665
2666 assert((T->isVoidType() || !T->isIncompleteType()) &&
2667 "Scalar types should always be complete");
2668 return false;
2669}
2670
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002671static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2672 SourceLocation Loc,
2673 SourceRange ArgRange,
2674 UnaryExprOrTypeTrait TraitKind) {
2675 // C99 6.5.3.4p1:
2676 if (T->isFunctionType()) {
2677 // alignof(function) is allowed as an extension.
2678 if (TraitKind == UETT_SizeOf)
2679 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2680 return false;
2681 }
2682
2683 // Allow sizeof(void)/alignof(void) as an extension.
2684 if (T->isVoidType()) {
2685 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2686 return false;
2687 }
2688
2689 return true;
2690}
2691
2692static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2693 SourceLocation Loc,
2694 SourceRange ArgRange,
2695 UnaryExprOrTypeTrait TraitKind) {
2696 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2697 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2698 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2699 << T << (TraitKind == UETT_SizeOf)
2700 << ArgRange;
2701 return true;
2702 }
2703
2704 return false;
2705}
2706
Chandler Carruth9d342d02011-05-26 08:53:10 +00002707/// \brief Check the constrains on expression operands to unary type expression
2708/// and type traits.
2709///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002710/// Completes any types necessary and validates the constraints on the operand
2711/// expression. The logic mostly mirrors the type-based overload, but may modify
2712/// the expression as it completes the type for that expression through template
2713/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00002714bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002715 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002716 QualType ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002717
2718 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2719 // the result is the size of the referenced type."
2720 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2721 // result shall be the alignment of the referenced type."
2722 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2723 ExprTy = Ref->getPointeeType();
2724
2725 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00002726 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2727 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002728
2729 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00002730 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2731 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002732 return false;
2733
Richard Trieuccd891a2011-09-09 01:45:06 +00002734 if (RequireCompleteExprType(E,
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002735 PDiag(diag::err_sizeof_alignof_incomplete_type)
Richard Trieuccd891a2011-09-09 01:45:06 +00002736 << ExprKind << E->getSourceRange(),
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002737 std::make_pair(SourceLocation(), PDiag(0))))
2738 return true;
2739
2740 // Completeing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00002741 ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002742 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2743 ExprTy = Ref->getPointeeType();
2744
Richard Trieuccd891a2011-09-09 01:45:06 +00002745 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2746 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002747 return true;
2748
Nico Webercf739922011-06-15 02:47:03 +00002749 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002750 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00002751 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2752 QualType OType = PVD->getOriginalType();
2753 QualType Type = PVD->getType();
2754 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002755 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00002756 << Type << OType;
2757 Diag(PVD->getLocation(), diag::note_declared_at);
2758 }
2759 }
2760 }
2761 }
2762
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002763 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00002764}
2765
2766/// \brief Check the constraints on operands to unary expression and type
2767/// traits.
2768///
2769/// This will complete any types necessary, and validate the various constraints
2770/// on those operands.
2771///
Reid Spencer5f016e22007-07-11 17:01:13 +00002772/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002773/// C99 6.3.2.1p[2-4] all state:
2774/// Except when it is the operand of the sizeof operator ...
2775///
2776/// C++ [expr.sizeof]p4
2777/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2778/// standard conversions are not applied to the operand of sizeof.
2779///
2780/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00002781bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002782 SourceLocation OpLoc,
2783 SourceRange ExprRange,
2784 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002785 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00002786 return false;
2787
Sebastian Redl5d484e82009-11-23 17:18:46 +00002788 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2789 // the result is the size of the referenced type."
2790 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2791 // result shall be the alignment of the referenced type."
Richard Trieuccd891a2011-09-09 01:45:06 +00002792 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2793 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00002794
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002795 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00002796 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002797
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002798 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00002799 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002800 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00002801 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002802
Richard Trieuccd891a2011-09-09 01:45:06 +00002803 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002804 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002805 << ExprKind << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002806 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002807
Richard Trieuccd891a2011-09-09 01:45:06 +00002808 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002809 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00002810 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002811
Chris Lattner1efaa952009-04-24 00:30:45 +00002812 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002813}
2814
Chandler Carruth9d342d02011-05-26 08:53:10 +00002815static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00002816 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002817
Mike Stump1eb44332009-09-09 15:08:12 +00002818 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002819 if (isa<DeclRefExpr>(E))
2820 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002821
2822 // Cannot know anything else if the expression is dependent.
2823 if (E->isTypeDependent())
2824 return false;
2825
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002826 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002827 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2828 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002829 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002830 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002831
2832 // Alignment of a field access is always okay, so long as it isn't a
2833 // bit-field.
2834 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002835 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002836 return false;
2837
Chandler Carruth9d342d02011-05-26 08:53:10 +00002838 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002839}
2840
Chandler Carruth9d342d02011-05-26 08:53:10 +00002841bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002842 E = E->IgnoreParens();
2843
2844 // Cannot know anything else if the expression is dependent.
2845 if (E->isTypeDependent())
2846 return false;
2847
Chandler Carruth9d342d02011-05-26 08:53:10 +00002848 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00002849}
2850
Douglas Gregorba498172009-03-13 21:01:28 +00002851/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002852ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002853Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2854 SourceLocation OpLoc,
2855 UnaryExprOrTypeTrait ExprKind,
2856 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002857 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002858 return ExprError();
2859
John McCalla93c9342009-12-07 02:54:59 +00002860 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002861
Douglas Gregorba498172009-03-13 21:01:28 +00002862 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002863 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00002864 return ExprError();
2865
2866 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002867 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2868 Context.getSizeType(),
2869 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002870}
2871
2872/// \brief Build a sizeof or alignof expression given an expression
2873/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002874ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002875Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2876 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00002877 ExprResult PE = CheckPlaceholderExpr(E);
2878 if (PE.isInvalid())
2879 return ExprError();
2880
2881 E = PE.get();
2882
Douglas Gregorba498172009-03-13 21:01:28 +00002883 // Verify that the operand is valid.
2884 bool isInvalid = false;
2885 if (E->isTypeDependent()) {
2886 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002887 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002888 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002889 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002890 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002891 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002892 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00002893 isInvalid = true;
2894 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002895 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00002896 }
2897
2898 if (isInvalid)
2899 return ExprError();
2900
2901 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002902 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002903 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002904 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002905}
2906
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002907/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2908/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00002909/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00002910ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002911Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00002912 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002913 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002914 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002915 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002916
Richard Trieuccd891a2011-09-09 01:45:06 +00002917 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00002918 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00002919 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002920 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002921 }
Sebastian Redl05189992008-11-11 17:56:53 +00002922
Douglas Gregorba498172009-03-13 21:01:28 +00002923 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002924 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregorba498172009-03-13 21:01:28 +00002925 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002926}
2927
John Wiegley429bb272011-04-08 18:41:53 +00002928static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00002929 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00002930 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00002931 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002932
John McCallf6a16482010-12-04 03:47:34 +00002933 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00002934 if (V.get()->getObjectKind() != OK_Ordinary) {
2935 V = S.DefaultLvalueConversion(V.take());
2936 if (V.isInvalid())
2937 return QualType();
2938 }
John McCallf6a16482010-12-04 03:47:34 +00002939
Chris Lattnercc26ed72007-08-26 05:39:26 +00002940 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00002941 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002942 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002943
Chris Lattnercc26ed72007-08-26 05:39:26 +00002944 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00002945 if (V.get()->getType()->isArithmeticType())
2946 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002947
John McCall2cd11fe2010-10-12 02:09:17 +00002948 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00002949 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00002950 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00002951 if (PR.get() != V.get()) {
2952 V = move(PR);
Richard Trieuccd891a2011-09-09 01:45:06 +00002953 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00002954 }
2955
Chris Lattnercc26ed72007-08-26 05:39:26 +00002956 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00002957 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00002958 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00002959 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00002960}
2961
2962
Reid Spencer5f016e22007-07-11 17:01:13 +00002963
John McCall60d7b3a2010-08-24 06:29:42 +00002964ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00002965Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002966 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00002967 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00002968 switch (Kind) {
2969 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00002970 case tok::plusplus: Opc = UO_PostInc; break;
2971 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002972 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002973
John McCall9ae2f072010-08-23 23:25:46 +00002974 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002975}
2976
John McCall60d7b3a2010-08-24 06:29:42 +00002977ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002978Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2979 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00002980 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00002981 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00002982 if (Result.isInvalid()) return ExprError();
2983 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002984
John McCall9ae2f072010-08-23 23:25:46 +00002985 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00002986
Douglas Gregor337c6b92008-11-19 17:17:41 +00002987 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002988 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002989 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00002990 Context.DependentTy,
2991 VK_LValue, OK_Ordinary,
2992 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002993 }
2994
Mike Stump1eb44332009-09-09 15:08:12 +00002995 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00002996 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00002997 LHSExp->getType()->isEnumeralType() ||
2998 RHSExp->getType()->isRecordType() ||
2999 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00003000 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003001 }
3002
John McCall9ae2f072010-08-23 23:25:46 +00003003 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003004}
3005
3006
John McCall60d7b3a2010-08-24 06:29:42 +00003007ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003008Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003009 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00003010 Expr *LHSExp = Base;
3011 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003012
Chris Lattner12d9ff62007-07-16 00:14:47 +00003013 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003014 if (!LHSExp->getType()->getAs<VectorType>()) {
3015 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3016 if (Result.isInvalid())
3017 return ExprError();
3018 LHSExp = Result.take();
3019 }
3020 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3021 if (Result.isInvalid())
3022 return ExprError();
3023 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003024
Chris Lattner12d9ff62007-07-16 00:14:47 +00003025 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003026 ExprValueKind VK = VK_LValue;
3027 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003028
Reid Spencer5f016e22007-07-11 17:01:13 +00003029 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003030 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003031 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003032 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003033 Expr *BaseExpr, *IndexExpr;
3034 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003035 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3036 BaseExpr = LHSExp;
3037 IndexExpr = RHSExp;
3038 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003039 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003040 BaseExpr = LHSExp;
3041 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003042 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003043 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00003044 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00003045 BaseExpr = RHSExp;
3046 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003047 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003048 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003049 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003050 BaseExpr = LHSExp;
3051 IndexExpr = RHSExp;
3052 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003053 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003054 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003055 // Handle the uncommon case of "123[Ptr]".
3056 BaseExpr = RHSExp;
3057 IndexExpr = LHSExp;
3058 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003059 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003060 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003061 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003062 VK = LHSExp->getValueKind();
3063 if (VK != VK_RValue)
3064 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003065
Chris Lattner12d9ff62007-07-16 00:14:47 +00003066 // FIXME: need to deal with const...
3067 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003068 } else if (LHSTy->isArrayType()) {
3069 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003070 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003071 // wasn't promoted because of the C90 rule that doesn't
3072 // allow promoting non-lvalue arrays. Warn, then
3073 // force the promotion here.
3074 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3075 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003076 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3077 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003078 LHSTy = LHSExp->getType();
3079
3080 BaseExpr = LHSExp;
3081 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003082 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003083 } else if (RHSTy->isArrayType()) {
3084 // Same as previous, except for 123[f().a] case
3085 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3086 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003087 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3088 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003089 RHSTy = RHSExp->getType();
3090
3091 BaseExpr = RHSExp;
3092 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003093 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003094 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003095 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3096 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003097 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003098 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003099 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003100 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3101 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003102
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003103 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003104 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3105 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003106 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3107
Douglas Gregore7450f52009-03-24 19:52:54 +00003108 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003109 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3110 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003111 // incomplete types are not object types.
3112 if (ResultType->isFunctionType()) {
3113 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3114 << ResultType << BaseExpr->getSourceRange();
3115 return ExprError();
3116 }
Mike Stump1eb44332009-09-09 15:08:12 +00003117
Abramo Bagnara46358452010-09-13 06:50:07 +00003118 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3119 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003120 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3121 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003122
3123 // C forbids expressions of unqualified void type from being l-values.
3124 // See IsCForbiddenLValueType.
3125 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003126 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003127 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003128 PDiag(diag::err_subscript_incomplete_type)
3129 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003130 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003131
Chris Lattner1efaa952009-04-24 00:30:45 +00003132 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003133 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003134 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3135 << ResultType << BaseExpr->getSourceRange();
3136 return ExprError();
3137 }
Mike Stump1eb44332009-09-09 15:08:12 +00003138
John McCall09431682010-11-18 19:01:18 +00003139 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003140 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003141
Mike Stumpeed9cac2009-02-19 03:04:26 +00003142 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003143 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003144}
3145
John McCall60d7b3a2010-08-24 06:29:42 +00003146ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003147 FunctionDecl *FD,
3148 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003149 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003150 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003151 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003152 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003153 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003154 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003155 return ExprError();
3156 }
3157
3158 if (Param->hasUninstantiatedDefaultArg()) {
3159 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003160
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003161 // Instantiate the expression.
3162 MultiLevelTemplateArgumentList ArgList
3163 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003164
Nico Weber08e41a62010-11-29 18:19:25 +00003165 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003166 = ArgList.getInnermost();
3167 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3168 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003169
Nico Weber08e41a62010-11-29 18:19:25 +00003170 ExprResult Result;
3171 {
3172 // C++ [dcl.fct.default]p5:
3173 // The names in the [default argument] expression are bound, and
3174 // the semantic constraints are checked, at the point where the
3175 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003176 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00003177 Result = SubstExpr(UninstExpr, ArgList);
3178 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003179 if (Result.isInvalid())
3180 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003181
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003182 // Check the expression as an initializer for the parameter.
3183 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003184 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003185 InitializationKind Kind
3186 = InitializationKind::CreateCopy(Param->getLocation(),
3187 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3188 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003189
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003190 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3191 Result = InitSeq.Perform(*this, Entity, Kind,
3192 MultiExprArg(*this, &ResultE, 1));
3193 if (Result.isInvalid())
3194 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003195
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003196 // Build the default argument expression.
3197 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3198 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003199 }
3200
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003201 // If the default expression creates temporaries, we need to
3202 // push them to the current stack of expression temporaries so they'll
3203 // be properly destroyed.
3204 // FIXME: We should really be rebuilding the default argument with new
3205 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003206 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3207 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3208 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3209 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3210 ExprTemporaries.push_back(Temporary);
John McCallf85e1932011-06-15 23:02:42 +00003211 ExprNeedsCleanups = true;
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003212 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003213
3214 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003215 // Just mark all of the declarations in this potentially-evaluated expression
3216 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003217 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00003218 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003219}
3220
Douglas Gregor88a35142008-12-22 05:46:06 +00003221/// ConvertArgumentsForCall - Converts the arguments specified in
3222/// Args/NumArgs to the parameter types of the function FDecl with
3223/// function prototype Proto. Call is the call expression itself, and
3224/// Fn is the function expression. For a C++ member function, this
3225/// routine does not attempt to convert the object argument. Returns
3226/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003227bool
3228Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003229 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003230 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003231 Expr **Args, unsigned NumArgs,
3232 SourceLocation RParenLoc) {
John McCall8e10f3b2011-02-26 05:39:39 +00003233 // Bail out early if calling a builtin with custom typechecking.
3234 // We don't need to do this in the
3235 if (FDecl)
3236 if (unsigned ID = FDecl->getBuiltinID())
3237 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3238 return false;
3239
Mike Stumpeed9cac2009-02-19 03:04:26 +00003240 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003241 // assignment, to the types of the corresponding parameter, ...
3242 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003243 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003244
Douglas Gregor88a35142008-12-22 05:46:06 +00003245 // If too few arguments are available (and we don't have default
3246 // arguments for the remaining parameters), don't make the call.
3247 if (NumArgs < NumArgsInProto) {
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003248 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) {
3249 Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003250 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00003251 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003252
3253 // Emit the location of the prototype.
3254 if (FDecl && !FDecl->getBuiltinID())
3255 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3256 << FDecl;
3257
3258 return true;
3259 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003260 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003261 }
3262
3263 // If too many are passed and not variadic, error on the extras and drop
3264 // them.
3265 if (NumArgs > NumArgsInProto) {
3266 if (!Proto->isVariadic()) {
3267 Diag(Args[NumArgsInProto]->getLocStart(),
3268 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003269 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00003270 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00003271 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3272 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003273
3274 // Emit the location of the prototype.
3275 if (FDecl && !FDecl->getBuiltinID())
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003276 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3277 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003278
Douglas Gregor88a35142008-12-22 05:46:06 +00003279 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003280 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003281 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003282 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003283 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003284 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003285 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003286 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3287 if (Fn->getType()->isBlockPointerType())
3288 CallType = VariadicBlock; // Block
3289 else if (isa<MemberExpr>(Fn))
3290 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003291 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003292 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003293 if (Invalid)
3294 return true;
3295 unsigned TotalNumArgs = AllArgs.size();
3296 for (unsigned i = 0; i < TotalNumArgs; ++i)
3297 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003298
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003299 return false;
3300}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003301
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003302bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3303 FunctionDecl *FDecl,
3304 const FunctionProtoType *Proto,
3305 unsigned FirstProtoArg,
3306 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003307 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003308 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003309 unsigned NumArgsInProto = Proto->getNumArgs();
3310 unsigned NumArgsToCheck = NumArgs;
3311 bool Invalid = false;
3312 if (NumArgs != NumArgsInProto)
3313 // Use default arguments for missing arguments
3314 NumArgsToCheck = NumArgsInProto;
3315 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003316 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003317 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003318 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003319
Douglas Gregor88a35142008-12-22 05:46:06 +00003320 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003321 if (ArgIx < NumArgs) {
3322 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003323
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003324 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3325 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003326 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003327 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003328 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003329
Douglas Gregora188ff22009-12-22 16:09:06 +00003330 // Pass the argument
3331 ParmVarDecl *Param = 0;
3332 if (FDecl && i < FDecl->getNumParams())
3333 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003334
Douglas Gregora188ff22009-12-22 16:09:06 +00003335 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003336 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003337 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3338 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003339 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003340 SourceLocation(),
3341 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00003342 if (ArgE.isInvalid())
3343 return true;
3344
3345 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003346 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003347 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003348
John McCall60d7b3a2010-08-24 06:29:42 +00003349 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003350 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003351 if (ArgExpr.isInvalid())
3352 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003353
Anders Carlsson56c5e332009-08-25 03:49:14 +00003354 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003355 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003356
3357 // Check for array bounds violations for each argument to the call. This
3358 // check only triggers warnings when the argument isn't a more complex Expr
3359 // with its own checking, such as a BinaryOperator.
3360 CheckArrayAccess(Arg);
3361
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003362 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003363 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003364
Douglas Gregor88a35142008-12-22 05:46:06 +00003365 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003366 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003367
3368 // Assume that extern "C" functions with variadic arguments that
3369 // return __unknown_anytype aren't *really* variadic.
3370 if (Proto->getResultType() == Context.UnknownAnyTy &&
3371 FDecl && FDecl->isExternC()) {
3372 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3373 ExprResult arg;
3374 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3375 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3376 else
3377 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3378 Invalid |= arg.isInvalid();
3379 AllArgs.push_back(arg.take());
3380 }
3381
3382 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3383 } else {
3384 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003385 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3386 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003387 Invalid |= Arg.isInvalid();
3388 AllArgs.push_back(Arg.take());
3389 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003390 }
3391 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003392 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003393}
3394
John McCall755d8492011-04-12 00:42:48 +00003395/// Given a function expression of unknown-any type, try to rebuild it
3396/// to have a function type.
3397static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3398
Steve Narofff69936d2007-09-16 03:34:24 +00003399/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003400/// This provides the location of the left/right parens and a list of comma
3401/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003402ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003403Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003404 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003405 Expr *ExecConfig) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003406 unsigned NumArgs = ArgExprs.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003407
3408 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003409 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003410 if (Result.isInvalid()) return ExprError();
3411 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003412
Richard Trieuccd891a2011-09-09 01:45:06 +00003413 Expr **Args = ArgExprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003414
Douglas Gregor88a35142008-12-22 05:46:06 +00003415 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003416 // If this is a pseudo-destructor expression, build the call immediately.
3417 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3418 if (NumArgs > 0) {
3419 // Pseudo-destructor calls should not have any arguments.
3420 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003421 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003422 SourceRange(Args[0]->getLocStart(),
3423 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003424
Douglas Gregora71d8192009-09-04 17:36:40 +00003425 NumArgs = 0;
3426 }
Mike Stump1eb44332009-09-09 15:08:12 +00003427
Douglas Gregora71d8192009-09-04 17:36:40 +00003428 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00003429 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003430 }
Mike Stump1eb44332009-09-09 15:08:12 +00003431
Douglas Gregor17330012009-02-04 15:01:18 +00003432 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003433 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003434 // FIXME: Will need to cache the results of name lookup (including ADL) in
3435 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003436 bool Dependent = false;
3437 if (Fn->isTypeDependent())
3438 Dependent = true;
3439 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3440 Dependent = true;
3441
Peter Collingbournee08ce652011-02-09 21:07:24 +00003442 if (Dependent) {
3443 if (ExecConfig) {
3444 return Owned(new (Context) CUDAKernelCallExpr(
3445 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3446 Context.DependentTy, VK_RValue, RParenLoc));
3447 } else {
3448 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3449 Context.DependentTy, VK_RValue,
3450 RParenLoc));
3451 }
3452 }
Douglas Gregor17330012009-02-04 15:01:18 +00003453
3454 // Determine whether this is a call to an object (C++ [over.call.object]).
3455 if (Fn->getType()->isRecordType())
3456 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003457 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003458
John McCall755d8492011-04-12 00:42:48 +00003459 if (Fn->getType() == Context.UnknownAnyTy) {
3460 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3461 if (result.isInvalid()) return ExprError();
3462 Fn = result.take();
3463 }
3464
John McCall864c0412011-04-26 20:42:42 +00003465 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00003466 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003467 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003468 }
John McCall864c0412011-04-26 20:42:42 +00003469 }
John McCall129e2df2009-11-30 22:42:35 +00003470
John McCall864c0412011-04-26 20:42:42 +00003471 // Check for overloaded calls. This can happen even in C due to extensions.
3472 if (Fn->getType() == Context.OverloadTy) {
3473 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3474
3475 // We aren't supposed to apply this logic if there's an '&' involved.
3476 if (!find.IsAddressOfOperand) {
3477 OverloadExpr *ovl = find.Expression;
3478 if (isa<UnresolvedLookupExpr>(ovl)) {
3479 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3480 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3481 RParenLoc, ExecConfig);
3482 } else {
John McCallaa81e162009-12-01 22:10:20 +00003483 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003484 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003485 }
3486 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003487 }
3488
Douglas Gregorfa047642009-02-04 00:32:51 +00003489 // If we're directly calling a function, get the appropriate declaration.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003490
Eli Friedmanefa42f72009-12-26 03:35:45 +00003491 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003492
John McCall3b4294e2009-12-16 12:17:52 +00003493 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003494 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3495 if (UnOp->getOpcode() == UO_AddrOf)
3496 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3497
John McCall3b4294e2009-12-16 12:17:52 +00003498 if (isa<DeclRefExpr>(NakedFn))
3499 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003500 else if (isa<MemberExpr>(NakedFn))
3501 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003502
Peter Collingbournee08ce652011-02-09 21:07:24 +00003503 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3504 ExecConfig);
3505}
3506
3507ExprResult
3508Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003509 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbournee08ce652011-02-09 21:07:24 +00003510 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3511 if (!ConfigDecl)
3512 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3513 << "cudaConfigureCall");
3514 QualType ConfigQTy = ConfigDecl->getType();
3515
3516 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3517 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3518
Richard Trieuccd891a2011-09-09 01:45:06 +00003519 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0);
John McCallaa81e162009-12-01 22:10:20 +00003520}
3521
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003522/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3523///
3524/// __builtin_astype( value, dst type )
3525///
Richard Trieuccd891a2011-09-09 01:45:06 +00003526ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003527 SourceLocation BuiltinLoc,
3528 SourceLocation RParenLoc) {
3529 ExprValueKind VK = VK_RValue;
3530 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00003531 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3532 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003533 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3534 return ExprError(Diag(BuiltinLoc,
3535 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003536 << DstTy
3537 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00003538 << E->getSourceRange());
3539 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieu67e29332011-08-02 04:35:43 +00003540 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003541}
3542
John McCall3b4294e2009-12-16 12:17:52 +00003543/// BuildResolvedCallExpr - Build a call to a resolved expression,
3544/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003545/// unary-convert to an expression of function-pointer or
3546/// block-pointer type.
3547///
3548/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003549ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003550Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3551 SourceLocation LParenLoc,
3552 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003553 SourceLocation RParenLoc,
3554 Expr *Config) {
John McCallaa81e162009-12-01 22:10:20 +00003555 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3556
Chris Lattner04421082008-04-08 04:40:51 +00003557 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00003558 ExprResult Result = UsualUnaryConversions(Fn);
3559 if (Result.isInvalid())
3560 return ExprError();
3561 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00003562
Chris Lattner925e60d2007-12-28 05:29:59 +00003563 // Make the call expr early, before semantic checks. This guarantees cleanup
3564 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00003565 CallExpr *TheCall;
3566 if (Config) {
3567 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3568 cast<CallExpr>(Config),
3569 Args, NumArgs,
3570 Context.BoolTy,
3571 VK_RValue,
3572 RParenLoc);
3573 } else {
3574 TheCall = new (Context) CallExpr(Context, Fn,
3575 Args, NumArgs,
3576 Context.BoolTy,
3577 VK_RValue,
3578 RParenLoc);
3579 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003580
John McCall8e10f3b2011-02-26 05:39:39 +00003581 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3582
3583 // Bail out early if calling a builtin with custom typechecking.
3584 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3585 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3586
John McCall1de4d4e2011-04-07 08:22:57 +00003587 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00003588 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00003589 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00003590 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3591 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00003592 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00003593 if (FuncT == 0)
3594 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3595 << Fn->getType() << Fn->getSourceRange());
3596 } else if (const BlockPointerType *BPT =
3597 Fn->getType()->getAs<BlockPointerType>()) {
3598 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3599 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00003600 // Handle calls to expressions of unknown-any type.
3601 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00003602 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003603 if (rewrite.isInvalid()) return ExprError();
3604 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00003605 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003606 goto retry;
3607 }
3608
Sebastian Redl0eb23302009-01-19 00:08:26 +00003609 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3610 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00003611 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003612
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003613 if (getLangOptions().CUDA) {
3614 if (Config) {
3615 // CUDA: Kernel calls must be to global functions
3616 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3617 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3618 << FDecl->getName() << Fn->getSourceRange());
3619
3620 // CUDA: Kernel function must have 'void' return type
3621 if (!FuncT->getResultType()->isVoidType())
3622 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3623 << Fn->getType() << Fn->getSourceRange());
3624 }
3625 }
3626
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003627 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003628 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00003629 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003630 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003631 return ExprError();
3632
Chris Lattner925e60d2007-12-28 05:29:59 +00003633 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003634 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00003635 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003636
Douglas Gregor72564e72009-02-26 23:50:07 +00003637 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00003638 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003639 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003640 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003641 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003642 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003643
Douglas Gregor74734d52009-04-02 15:37:10 +00003644 if (FDecl) {
3645 // Check if we have too few/too many template arguments, based
3646 // on our knowledge of the function definition.
3647 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00003648 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003649 const FunctionProtoType *Proto
3650 = Def->getType()->getAs<FunctionProtoType>();
3651 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003652 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3653 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003654 }
Douglas Gregor46542412010-10-25 20:39:23 +00003655
3656 // If the function we're calling isn't a function prototype, but we have
3657 // a function prototype from a prior declaratiom, use that prototype.
3658 if (!FDecl->hasPrototype())
3659 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00003660 }
3661
Steve Naroffb291ab62007-08-28 23:30:39 +00003662 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003663 for (unsigned i = 0; i != NumArgs; i++) {
3664 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00003665
3666 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003667 InitializedEntity Entity
3668 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00003669 Proto->getArgType(i),
3670 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00003671 ExprResult ArgE = PerformCopyInitialization(Entity,
3672 SourceLocation(),
3673 Owned(Arg));
3674 if (ArgE.isInvalid())
3675 return true;
3676
3677 Arg = ArgE.takeAs<Expr>();
3678
3679 } else {
John Wiegley429bb272011-04-08 18:41:53 +00003680 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3681
3682 if (ArgE.isInvalid())
3683 return true;
3684
3685 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00003686 }
3687
Douglas Gregor0700bbf2010-10-26 05:45:40 +00003688 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3689 Arg->getType(),
3690 PDiag(diag::err_call_incomplete_argument)
3691 << Arg->getSourceRange()))
3692 return ExprError();
3693
Chris Lattner925e60d2007-12-28 05:29:59 +00003694 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003695 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003696 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003697
Douglas Gregor88a35142008-12-22 05:46:06 +00003698 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3699 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003700 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3701 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003702
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003703 // Check for sentinels
3704 if (NDecl)
3705 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003706
Chris Lattner59907c42007-08-10 20:18:51 +00003707 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003708 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003709 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003710 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003711
John McCall8e10f3b2011-02-26 05:39:39 +00003712 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00003713 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00003714 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003715 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003716 return ExprError();
3717 }
Chris Lattner59907c42007-08-10 20:18:51 +00003718
John McCall9ae2f072010-08-23 23:25:46 +00003719 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00003720}
3721
John McCall60d7b3a2010-08-24 06:29:42 +00003722ExprResult
John McCallb3d87482010-08-24 05:47:05 +00003723Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00003724 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003725 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00003726 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003727 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00003728
3729 TypeSourceInfo *TInfo;
3730 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3731 if (!TInfo)
3732 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3733
John McCall9ae2f072010-08-23 23:25:46 +00003734 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00003735}
3736
John McCall60d7b3a2010-08-24 06:29:42 +00003737ExprResult
John McCall42f56b52010-01-18 19:35:47 +00003738Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00003739 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00003740 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00003741
Eli Friedman6223c222008-05-20 05:22:08 +00003742 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00003743 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3744 PDiag(diag::err_illegal_decl_array_incomplete_type)
3745 << SourceRange(LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003746 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00003747 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003748 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003749 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00003750 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003751 } else if (!literalType->isDependentType() &&
3752 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003753 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003754 << SourceRange(LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003755 LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003756 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003757
Douglas Gregor99a2e602009-12-16 01:38:02 +00003758 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003759 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003760 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00003761 = InitializationKind::CreateCStyleCast(LParenLoc,
3762 SourceRange(LParenLoc, RParenLoc));
Richard Trieuccd891a2011-09-09 01:45:06 +00003763 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00003764 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuccd891a2011-09-09 01:45:06 +00003765 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00003766 &literalType);
3767 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003768 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00003769 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00003770
Chris Lattner371f2582008-12-04 23:50:19 +00003771 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003772 if (isFileScope) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00003773 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003774 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003775 }
Eli Friedman08544622009-12-22 02:35:53 +00003776
John McCallf89e55a2010-11-18 06:31:45 +00003777 // In C, compound literals are l-values for some reason.
3778 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3779
Douglas Gregor751ec9b2011-06-17 04:59:12 +00003780 return MaybeBindToTemporary(
3781 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00003782 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003783}
3784
John McCall60d7b3a2010-08-24 06:29:42 +00003785ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00003786Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003787 SourceLocation RBraceLoc) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003788 unsigned NumInit = InitArgList.size();
3789 Expr **InitList = InitArgList.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003790
Steve Naroff08d92e42007-09-15 18:49:24 +00003791 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003792 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003793
Ted Kremenek709210f2010-04-13 23:39:13 +00003794 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3795 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003796 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003797 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003798}
3799
John McCallf3ea8cf2010-11-14 08:17:51 +00003800/// Prepares for a scalar cast, performing all the necessary stages
3801/// except the final cast and returning the kind required.
John Wiegley429bb272011-04-08 18:41:53 +00003802static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00003803 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3804 // Also, callers should have filtered out the invalid cases with
3805 // pointers. Everything else should be possible.
3806
John Wiegley429bb272011-04-08 18:41:53 +00003807 QualType SrcTy = Src.get()->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00003808 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00003809 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00003810
John McCall1d9b3b22011-09-09 05:25:32 +00003811 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00003812 case Type::STK_MemberPointer:
3813 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003814
John McCall1d9b3b22011-09-09 05:25:32 +00003815 case Type::STK_CPointer:
3816 case Type::STK_BlockPointer:
3817 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00003818 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00003819 case Type::STK_CPointer:
3820 return CK_BitCast;
3821 case Type::STK_BlockPointer:
3822 return (SrcKind == Type::STK_BlockPointer
3823 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
3824 case Type::STK_ObjCObjectPointer:
3825 if (SrcKind == Type::STK_ObjCObjectPointer)
3826 return CK_BitCast;
3827 else if (SrcKind == Type::STK_CPointer)
3828 return CK_CPointerToObjCPointerCast;
3829 else
3830 return CK_BlockPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003831 case Type::STK_Bool:
3832 return CK_PointerToBoolean;
3833 case Type::STK_Integral:
3834 return CK_PointerToIntegral;
3835 case Type::STK_Floating:
3836 case Type::STK_FloatingComplex:
3837 case Type::STK_IntegralComplex:
3838 case Type::STK_MemberPointer:
3839 llvm_unreachable("illegal cast from pointer");
3840 }
3841 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003842
John McCalldaa8e4e2010-11-15 09:13:47 +00003843 case Type::STK_Bool: // casting from bool is like casting from an integer
3844 case Type::STK_Integral:
3845 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00003846 case Type::STK_CPointer:
3847 case Type::STK_ObjCObjectPointer:
3848 case Type::STK_BlockPointer:
Richard Trieu67e29332011-08-02 04:35:43 +00003849 if (Src.get()->isNullPointerConstant(S.Context,
3850 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00003851 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00003852 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00003853 case Type::STK_Bool:
3854 return CK_IntegralToBoolean;
3855 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00003856 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003857 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00003858 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00003859 case Type::STK_IntegralComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003860 Src = S.ImpCastExprToType(Src.take(),
3861 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003862 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00003863 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003864 case Type::STK_FloatingComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003865 Src = S.ImpCastExprToType(Src.take(),
3866 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003867 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00003868 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003869 case Type::STK_MemberPointer:
3870 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003871 }
3872 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003873
John McCalldaa8e4e2010-11-15 09:13:47 +00003874 case Type::STK_Floating:
3875 switch (DestTy->getScalarTypeKind()) {
3876 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00003877 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003878 case Type::STK_Bool:
3879 return CK_FloatingToBoolean;
3880 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00003881 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00003882 case Type::STK_FloatingComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003883 Src = S.ImpCastExprToType(Src.take(),
3884 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003885 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00003886 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003887 case Type::STK_IntegralComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003888 Src = S.ImpCastExprToType(Src.take(),
3889 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003890 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00003891 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00003892 case Type::STK_CPointer:
3893 case Type::STK_ObjCObjectPointer:
3894 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00003895 llvm_unreachable("valid float->pointer cast?");
3896 case Type::STK_MemberPointer:
3897 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003898 }
3899 break;
3900
John McCalldaa8e4e2010-11-15 09:13:47 +00003901 case Type::STK_FloatingComplex:
3902 switch (DestTy->getScalarTypeKind()) {
3903 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003904 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003905 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003906 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00003907 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003908 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00003909 if (S.Context.hasSameType(ET, DestTy))
3910 return CK_FloatingComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00003911 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00003912 return CK_FloatingCast;
3913 }
John McCalldaa8e4e2010-11-15 09:13:47 +00003914 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00003915 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00003916 case Type::STK_Integral:
Richard Trieu67e29332011-08-02 04:35:43 +00003917 Src = S.ImpCastExprToType(Src.take(),
3918 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003919 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00003920 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00003921 case Type::STK_CPointer:
3922 case Type::STK_ObjCObjectPointer:
3923 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00003924 llvm_unreachable("valid complex float->pointer cast?");
3925 case Type::STK_MemberPointer:
3926 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003927 }
3928 break;
3929
John McCalldaa8e4e2010-11-15 09:13:47 +00003930 case Type::STK_IntegralComplex:
3931 switch (DestTy->getScalarTypeKind()) {
3932 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003933 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003934 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003935 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00003936 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003937 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00003938 if (S.Context.hasSameType(ET, DestTy))
3939 return CK_IntegralComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00003940 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00003941 return CK_IntegralCast;
3942 }
John McCalldaa8e4e2010-11-15 09:13:47 +00003943 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00003944 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00003945 case Type::STK_Floating:
Richard Trieu67e29332011-08-02 04:35:43 +00003946 Src = S.ImpCastExprToType(Src.take(),
3947 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003948 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00003949 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00003950 case Type::STK_CPointer:
3951 case Type::STK_ObjCObjectPointer:
3952 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00003953 llvm_unreachable("valid complex int->pointer cast?");
3954 case Type::STK_MemberPointer:
3955 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003956 }
3957 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00003958 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003959
John McCallf3ea8cf2010-11-14 08:17:51 +00003960 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00003961}
3962
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003963/// CheckCastTypes - Check type constraints for casting between types.
Richard Trieuccd891a2011-09-09 01:45:06 +00003964ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc,
3965 SourceRange TypeRange, QualType CastType,
3966 Expr *CastExpr, CastKind &Kind,
3967 ExprValueKind &VK, CXXCastPath &BasePath,
3968 bool FunctionalStyle) {
3969 if (CastExpr->getType() == Context.UnknownAnyTy)
3970 return checkUnknownAnyCast(TypeRange, CastType, CastExpr, Kind, VK,
3971 BasePath);
John McCall1de4d4e2011-04-07 08:22:57 +00003972
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003973 if (getLangOptions().CPlusPlus)
John McCallf85e1932011-06-15 23:02:42 +00003974 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003975 CastExpr->getLocEnd()),
3976 CastType, VK, CastExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003977 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003978
Richard Trieuccd891a2011-09-09 01:45:06 +00003979 assert(!CastExpr->getType()->isPlaceholderType());
John McCallfb8721c2011-04-10 19:13:55 +00003980
John McCallf89e55a2010-11-18 06:31:45 +00003981 // We only support r-value casts in C.
3982 VK = VK_RValue;
3983
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003984 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3985 // type needs to be scalar.
Richard Trieuccd891a2011-09-09 01:45:06 +00003986 if (CastType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00003987 // We don't necessarily do lvalue-to-rvalue conversions on this.
Richard Trieuccd891a2011-09-09 01:45:06 +00003988 ExprResult castExprRes = IgnoredValueConversions(CastExpr);
John Wiegley429bb272011-04-08 18:41:53 +00003989 if (castExprRes.isInvalid())
3990 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00003991 CastExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00003992
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003993 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00003994 Kind = CK_ToVoid;
Richard Trieuccd891a2011-09-09 01:45:06 +00003995 return Owned(CastExpr);
Anders Carlssonebeaf202009-10-16 02:35:04 +00003996 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003997
Richard Trieuccd891a2011-09-09 01:45:06 +00003998 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(CastExpr);
John Wiegley429bb272011-04-08 18:41:53 +00003999 if (castExprRes.isInvalid())
4000 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004001 CastExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00004002
Richard Trieuccd891a2011-09-09 01:45:06 +00004003 if (RequireCompleteType(TypeRange.getBegin(), CastType,
Eli Friedman8d438082010-07-17 20:43:49 +00004004 diag::err_typecheck_cast_to_incomplete))
John Wiegley429bb272011-04-08 18:41:53 +00004005 return ExprError();
Eli Friedman8d438082010-07-17 20:43:49 +00004006
Richard Trieuccd891a2011-09-09 01:45:06 +00004007 if (!CastType->isScalarType() && !CastType->isVectorType()) {
4008 if (Context.hasSameUnqualifiedType(CastType, CastExpr->getType()) &&
4009 (CastType->isStructureType() || CastType->isUnionType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004010 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004011 // FIXME: Check that the cast destination type is complete.
Richard Trieuccd891a2011-09-09 01:45:06 +00004012 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
4013 << CastType << CastExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004014 Kind = CK_NoOp;
Richard Trieuccd891a2011-09-09 01:45:06 +00004015 return Owned(CastExpr);
Anders Carlssonc3516322009-10-16 02:48:28 +00004016 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004017
Richard Trieuccd891a2011-09-09 01:45:06 +00004018 if (CastType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004019 // GCC cast to union extension
Richard Trieuccd891a2011-09-09 01:45:06 +00004020 RecordDecl *RD = CastType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004021 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004022 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004023 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004024 if (Context.hasSameUnqualifiedType(Field->getType(),
Richard Trieuccd891a2011-09-09 01:45:06 +00004025 CastExpr->getType()) &&
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00004026 !Field->isUnnamedBitfield()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00004027 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_to_union)
4028 << CastExpr->getSourceRange();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004029 break;
4030 }
4031 }
John Wiegley429bb272011-04-08 18:41:53 +00004032 if (Field == FieldEnd) {
Richard Trieuccd891a2011-09-09 01:45:06 +00004033 Diag(TypeRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4034 << CastExpr->getType() << CastExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004035 return ExprError();
4036 }
John McCall2de56d12010-08-25 11:45:40 +00004037 Kind = CK_ToUnion;
Richard Trieuccd891a2011-09-09 01:45:06 +00004038 return Owned(CastExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004039 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004040
Anders Carlssonc3516322009-10-16 02:48:28 +00004041 // Reject any other conversions to non-scalar types.
Richard Trieuccd891a2011-09-09 01:45:06 +00004042 Diag(TypeRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
4043 << CastType << CastExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004044 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00004045 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004046
John McCallf3ea8cf2010-11-14 08:17:51 +00004047 // The type we're casting to is known to be a scalar or vector.
4048
4049 // Require the operand to be a scalar or vector.
Richard Trieuccd891a2011-09-09 01:45:06 +00004050 if (!CastExpr->getType()->isScalarType() &&
4051 !CastExpr->getType()->isVectorType()) {
4052 Diag(CastExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004053 diag::err_typecheck_expect_scalar_operand)
Richard Trieuccd891a2011-09-09 01:45:06 +00004054 << CastExpr->getType() << CastExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004055 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00004056 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004057
Richard Trieuccd891a2011-09-09 01:45:06 +00004058 if (CastType->isExtVectorType())
4059 return CheckExtVectorCast(TypeRange, CastType, CastExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004060
Richard Trieuccd891a2011-09-09 01:45:06 +00004061 if (CastType->isVectorType()) {
4062 if (CastType->getAs<VectorType>()->getVectorKind() ==
Anton Yartsevd06fea82011-03-27 09:32:40 +00004063 VectorType::AltiVecVector &&
Richard Trieuccd891a2011-09-09 01:45:06 +00004064 (CastExpr->getType()->isIntegerType() ||
4065 CastExpr->getType()->isFloatingType())) {
Anton Yartsevd06fea82011-03-27 09:32:40 +00004066 Kind = CK_VectorSplat;
Richard Trieuccd891a2011-09-09 01:45:06 +00004067 return Owned(CastExpr);
4068 } else if (CheckVectorCast(TypeRange, CastType, CastExpr->getType(),
4069 Kind)) {
John Wiegley429bb272011-04-08 18:41:53 +00004070 return ExprError();
Anton Yartsevd06fea82011-03-27 09:32:40 +00004071 } else
Richard Trieuccd891a2011-09-09 01:45:06 +00004072 return Owned(CastExpr);
Anton Yartsevd06fea82011-03-27 09:32:40 +00004073 }
Richard Trieuccd891a2011-09-09 01:45:06 +00004074 if (CastExpr->getType()->isVectorType()) {
4075 if (CheckVectorCast(TypeRange, CastExpr->getType(), CastType, Kind))
John Wiegley429bb272011-04-08 18:41:53 +00004076 return ExprError();
4077 else
Richard Trieuccd891a2011-09-09 01:45:06 +00004078 return Owned(CastExpr);
John Wiegley429bb272011-04-08 18:41:53 +00004079 }
Anders Carlssonc3516322009-10-16 02:48:28 +00004080
John McCallf3ea8cf2010-11-14 08:17:51 +00004081 // The source and target types are both scalars, i.e.
4082 // - arithmetic types (fundamental, enum, and complex)
4083 // - all kinds of pointers
4084 // Note that member pointers were filtered out with C++, above.
4085
Richard Trieuccd891a2011-09-09 01:45:06 +00004086 if (isa<ObjCSelectorExpr>(CastExpr)) {
4087 Diag(CastExpr->getLocStart(), diag::err_cast_selector_expr);
John Wiegley429bb272011-04-08 18:41:53 +00004088 return ExprError();
4089 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004090
John McCallf3ea8cf2010-11-14 08:17:51 +00004091 // If either type is a pointer, the other type has to be either an
4092 // integer or a pointer.
Richard Trieuccd891a2011-09-09 01:45:06 +00004093 QualType CastExprType = CastExpr->getType();
4094 if (!CastType->isArithmeticType()) {
4095 if (!CastExprType->isIntegralType(Context) &&
4096 CastExprType->isArithmeticType()) {
4097 Diag(CastExpr->getLocStart(),
John Wiegley429bb272011-04-08 18:41:53 +00004098 diag::err_cast_pointer_from_non_pointer_int)
Richard Trieuccd891a2011-09-09 01:45:06 +00004099 << CastExprType << CastExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004100 return ExprError();
4101 }
Richard Trieuccd891a2011-09-09 01:45:06 +00004102 } else if (!CastExpr->getType()->isArithmeticType()) {
4103 if (!CastType->isIntegralType(Context) && CastType->isArithmeticType()) {
4104 Diag(CastExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
4105 << CastType << CastExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004106 return ExprError();
4107 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004108 }
Anders Carlsson82debc72009-10-18 18:12:03 +00004109
John McCallf85e1932011-06-15 23:02:42 +00004110 if (getLangOptions().ObjCAutoRefCount) {
4111 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
Richard Trieuccd891a2011-09-09 01:45:06 +00004112 CheckObjCARCConversion(SourceRange(CastStartLoc, CastExpr->getLocEnd()),
4113 CastType, CastExpr, CCK_CStyleCast);
John McCallf85e1932011-06-15 23:02:42 +00004114
Richard Trieuccd891a2011-09-09 01:45:06 +00004115 if (const PointerType *CastPtr = CastType->getAs<PointerType>()) {
4116 if (const PointerType *ExprPtr = CastExprType->getAs<PointerType>()) {
John McCallf85e1932011-06-15 23:02:42 +00004117 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4118 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4119 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4120 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4121 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
Richard Trieuccd891a2011-09-09 01:45:06 +00004122 Diag(CastExpr->getLocStart(),
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00004123 diag::err_typecheck_incompatible_ownership)
Richard Trieuccd891a2011-09-09 01:45:06 +00004124 << CastExprType << CastType << AA_Casting
4125 << CastExpr->getSourceRange();
John McCallf85e1932011-06-15 23:02:42 +00004126
4127 return ExprError();
4128 }
4129 }
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00004130 }
Richard Trieuccd891a2011-09-09 01:45:06 +00004131 else if (!CheckObjCARCUnavailableWeakConversion(CastType, CastExprType)) {
4132 Diag(CastExpr->getLocStart(),
Fariborz Jahanian82007c32011-07-08 17:41:42 +00004133 diag::err_arc_convesion_of_weak_unavailable) << 1
Richard Trieuccd891a2011-09-09 01:45:06 +00004134 << CastExprType << CastType
4135 << CastExpr->getSourceRange();
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00004136 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00004137 }
4138 }
4139
Richard Trieuccd891a2011-09-09 01:45:06 +00004140 castExprRes = Owned(CastExpr);
4141 Kind = PrepareScalarCast(*this, castExprRes, CastType);
John Wiegley429bb272011-04-08 18:41:53 +00004142 if (castExprRes.isInvalid())
4143 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004144 CastExpr = castExprRes.take();
John McCallb7f4ffe2010-08-12 21:44:57 +00004145
John McCallf3ea8cf2010-11-14 08:17:51 +00004146 if (Kind == CK_BitCast)
Richard Trieuccd891a2011-09-09 01:45:06 +00004147 CheckCastAlign(CastExpr, CastType, TypeRange);
John McCallb7f4ffe2010-08-12 21:44:57 +00004148
Richard Trieuccd891a2011-09-09 01:45:06 +00004149 return Owned(CastExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004150}
4151
Anders Carlssonc3516322009-10-16 02:48:28 +00004152bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004153 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004154 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004155
Anders Carlssona64db8f2007-11-27 05:51:55 +00004156 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004157 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004158 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004159 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004160 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004161 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004162 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004163 } else
4164 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004165 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004166 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004167
John McCall2de56d12010-08-25 11:45:40 +00004168 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004169 return false;
4170}
4171
John Wiegley429bb272011-04-08 18:41:53 +00004172ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4173 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004174 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004175
Anders Carlsson16a89042009-10-16 05:23:41 +00004176 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004177
Nate Begeman9b10da62009-06-27 22:05:55 +00004178 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4179 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00004180 if (SrcTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004181 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
4182 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004183 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004184 return ExprError();
4185 }
John McCall2de56d12010-08-25 11:45:40 +00004186 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004187 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004188 }
4189
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004190 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004191 // conversion will take place first from scalar to elt type, and then
4192 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004193 if (SrcTy->isPointerType())
4194 return Diag(R.getBegin(),
4195 diag::err_invalid_conversion_between_vector_and_scalar)
4196 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004197
4198 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004199 ExprResult CastExprRes = Owned(CastExpr);
4200 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4201 if (CastExprRes.isInvalid())
4202 return ExprError();
4203 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004204
John McCall2de56d12010-08-25 11:45:40 +00004205 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004206 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004207}
4208
John McCall60d7b3a2010-08-24 06:29:42 +00004209ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004210Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4211 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004212 SourceLocation RParenLoc, Expr *CastExpr) {
4213 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004214 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004215
Richard Trieuccd891a2011-09-09 01:45:06 +00004216 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004217 if (D.isInvalidType())
4218 return ExprError();
4219
4220 if (getLangOptions().CPlusPlus) {
4221 // Check that there are no default arguments (C++ only).
4222 CheckExtraCXXDefaultArguments(D);
4223 }
4224
4225 QualType castType = castTInfo->getType();
4226 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004227
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004228 bool isVectorLiteral = false;
4229
4230 // Check for an altivec or OpenCL literal,
4231 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00004232 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4233 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004234 if (getLangOptions().AltiVec && castType->isVectorType() && (PE || PLE)) {
4235 if (PLE && PLE->getNumExprs() == 0) {
4236 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4237 return ExprError();
4238 }
4239 if (PE || PLE->getNumExprs() == 1) {
4240 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4241 if (!E->getType()->isVectorType())
4242 isVectorLiteral = true;
4243 }
4244 else
4245 isVectorLiteral = true;
4246 }
4247
4248 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4249 // then handle it as such.
4250 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00004251 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004252
Nate Begeman2ef13e52009-08-10 23:49:36 +00004253 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004254 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4255 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00004256 if (isa<ParenListExpr>(CastExpr)) {
4257 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004258 if (Result.isInvalid()) return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004259 CastExpr = Result.take();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004260 }
John McCallb042fdf2010-01-15 18:56:44 +00004261
Richard Trieuccd891a2011-09-09 01:45:06 +00004262 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004263}
4264
John McCall60d7b3a2010-08-24 06:29:42 +00004265ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00004266Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004267 SourceLocation RParenLoc, Expr *CastExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004268 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00004269 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00004270 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +00004271 ExprResult CastResult =
John McCallf85e1932011-06-15 23:02:42 +00004272 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
Richard Trieuccd891a2011-09-09 01:45:06 +00004273 CastExpr, Kind, VK, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +00004274 if (CastResult.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004275 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004276 CastExpr = CastResult.take();
Anders Carlsson0aebc812009-09-09 21:33:21 +00004277
Richard Trieu67e29332011-08-02 04:35:43 +00004278 return Owned(CStyleCastExpr::Create(
Richard Trieuccd891a2011-09-09 01:45:06 +00004279 Context, Ty->getType().getNonLValueExprType(Context), VK, Kind, CastExpr,
Richard Trieu67e29332011-08-02 04:35:43 +00004280 &BasePath, Ty, LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00004281}
4282
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004283ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4284 SourceLocation RParenLoc, Expr *E,
4285 TypeSourceInfo *TInfo) {
4286 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4287 "Expected paren or paren list expression");
4288
4289 Expr **exprs;
4290 unsigned numExprs;
4291 Expr *subExpr;
4292 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4293 exprs = PE->getExprs();
4294 numExprs = PE->getNumExprs();
4295 } else {
4296 subExpr = cast<ParenExpr>(E)->getSubExpr();
4297 exprs = &subExpr;
4298 numExprs = 1;
4299 }
4300
4301 QualType Ty = TInfo->getType();
4302 assert(Ty->isVectorType() && "Expected vector type");
4303
Chris Lattner5f9e2722011-07-23 10:55:15 +00004304 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004305 const VectorType *VTy = Ty->getAs<VectorType>();
4306 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4307
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004308 // '(...)' form of vector initialization in AltiVec: the number of
4309 // initializers must be one or must match the size of the vector.
4310 // If a single value is specified in the initializer then it will be
4311 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004312 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004313 // The number of initializers must be one or must match the size of the
4314 // vector. If a single value is specified in the initializer then it will
4315 // be replicated to all the components of the vector
4316 if (numExprs == 1) {
4317 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4318 ExprResult Literal = Owned(exprs[0]);
4319 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4320 PrepareScalarCast(*this, Literal, ElemTy));
4321 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4322 }
4323 else if (numExprs < numElems) {
4324 Diag(E->getExprLoc(),
4325 diag::err_incorrect_number_of_vector_initializers);
4326 return ExprError();
4327 }
4328 else
4329 for (unsigned i = 0, e = numExprs; i != e; ++i)
4330 initExprs.push_back(exprs[i]);
4331 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004332 else {
4333 // For OpenCL, when the number of initializers is a single value,
4334 // it will be replicated to all components of the vector.
4335 if (getLangOptions().OpenCL &&
4336 VTy->getVectorKind() == VectorType::GenericVector &&
4337 numExprs == 1) {
4338 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4339 ExprResult Literal = Owned(exprs[0]);
4340 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4341 PrepareScalarCast(*this, Literal, ElemTy));
4342 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4343 }
4344
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004345 for (unsigned i = 0, e = numExprs; i != e; ++i)
4346 initExprs.push_back(exprs[i]);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004347 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004348 // FIXME: This means that pretty-printing the final AST will produce curly
4349 // braces instead of the original commas.
4350 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4351 &initExprs[0],
4352 initExprs.size(), RParenLoc);
4353 initE->setType(Ty);
4354 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4355}
4356
Nate Begeman2ef13e52009-08-10 23:49:36 +00004357/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4358/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004359ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004360Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4361 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004362 if (!E)
Richard Trieuccd891a2011-09-09 01:45:06 +00004363 return Owned(OrigExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004364
John McCall60d7b3a2010-08-24 06:29:42 +00004365 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004366
Nate Begeman2ef13e52009-08-10 23:49:36 +00004367 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004368 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4369 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004370
John McCall9ae2f072010-08-23 23:25:46 +00004371 if (Result.isInvalid()) return ExprError();
4372
4373 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004374}
4375
John McCall60d7b3a2010-08-24 06:29:42 +00004376ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Richard Trieuccd891a2011-09-09 01:45:06 +00004377 SourceLocation R,
4378 MultiExprArg Val) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004379 unsigned nexprs = Val.size();
4380 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004381 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4382 Expr *expr;
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004383 if (nexprs == 1)
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004384 expr = new (Context) ParenExpr(L, R, exprs[0]);
4385 else
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004386 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4387 exprs[nexprs-1]->getType());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004388 return Owned(expr);
4389}
4390
Chandler Carruth82214a82011-02-18 23:54:50 +00004391/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004392/// constant and the other is not a pointer. Returns true if a diagnostic is
4393/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00004394bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00004395 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004396 Expr *NullExpr = LHSExpr;
4397 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004398 Expr::NullPointerConstantKind NullKind =
4399 NullExpr->isNullPointerConstant(Context,
4400 Expr::NPC_ValueDependentIsNotNull);
4401
4402 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004403 NullExpr = RHSExpr;
4404 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004405 NullKind =
4406 NullExpr->isNullPointerConstant(Context,
4407 Expr::NPC_ValueDependentIsNotNull);
4408 }
4409
4410 if (NullKind == Expr::NPCK_NotNull)
4411 return false;
4412
4413 if (NullKind == Expr::NPCK_ZeroInteger) {
4414 // In this case, check to make sure that we got here from a "NULL"
4415 // string in the source code.
4416 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004417 SourceLocation loc = NullExpr->getExprLoc();
4418 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004419 return false;
4420 }
4421
4422 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4423 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4424 << NonPointerExpr->getType() << DiagType
4425 << NonPointerExpr->getSourceRange();
4426 return true;
4427}
4428
Richard Trieu26f96072011-09-02 01:51:02 +00004429/// \brief Return false if the condition expression is valid, true otherwise.
4430static bool checkCondition(Sema &S, Expr *Cond) {
4431 QualType CondTy = Cond->getType();
4432
4433 // C99 6.5.15p2
4434 if (CondTy->isScalarType()) return false;
4435
4436 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4437 if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4438 return false;
4439
4440 // Emit the proper error message.
4441 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4442 diag::err_typecheck_cond_expect_scalar :
4443 diag::err_typecheck_cond_expect_scalar_or_vector)
4444 << CondTy;
4445 return true;
4446}
4447
4448/// \brief Return false if the two expressions can be converted to a vector,
4449/// true otherwise
4450static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4451 ExprResult &RHS,
4452 QualType CondTy) {
4453 // Both operands should be of scalar type.
4454 if (!LHS.get()->getType()->isScalarType()) {
4455 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4456 << CondTy;
4457 return true;
4458 }
4459 if (!RHS.get()->getType()->isScalarType()) {
4460 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4461 << CondTy;
4462 return true;
4463 }
4464
4465 // Implicity convert these scalars to the type of the condition.
4466 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4467 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4468 return false;
4469}
4470
4471/// \brief Handle when one or both operands are void type.
4472static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4473 ExprResult &RHS) {
4474 Expr *LHSExpr = LHS.get();
4475 Expr *RHSExpr = RHS.get();
4476
4477 if (!LHSExpr->getType()->isVoidType())
4478 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4479 << RHSExpr->getSourceRange();
4480 if (!RHSExpr->getType()->isVoidType())
4481 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4482 << LHSExpr->getSourceRange();
4483 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4484 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4485 return S.Context.VoidTy;
4486}
4487
4488/// \brief Return false if the NullExpr can be promoted to PointerTy,
4489/// true otherwise.
4490static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4491 QualType PointerTy) {
4492 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4493 !NullExpr.get()->isNullPointerConstant(S.Context,
4494 Expr::NPC_ValueDependentIsNull))
4495 return true;
4496
4497 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4498 return false;
4499}
4500
4501/// \brief Checks compatibility between two pointers and return the resulting
4502/// type.
4503static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4504 ExprResult &RHS,
4505 SourceLocation Loc) {
4506 QualType LHSTy = LHS.get()->getType();
4507 QualType RHSTy = RHS.get()->getType();
4508
4509 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4510 // Two identical pointers types are always compatible.
4511 return LHSTy;
4512 }
4513
4514 QualType lhptee, rhptee;
4515
4516 // Get the pointee types.
John McCall1d9b3b22011-09-09 05:25:32 +00004517 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4518 lhptee = LHSBTy->getPointeeType();
4519 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004520 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00004521 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4522 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004523 }
4524
4525 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4526 rhptee.getUnqualifiedType())) {
4527 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4528 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4529 << RHS.get()->getSourceRange();
4530 // In this situation, we assume void* type. No especially good
4531 // reason, but this is what gcc does, and we do have to pick
4532 // to get a consistent AST.
4533 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4534 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4535 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4536 return incompatTy;
4537 }
4538
4539 // The pointer types are compatible.
4540 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4541 // differently qualified versions of compatible types, the result type is
4542 // a pointer to an appropriately qualified version of the *composite*
4543 // type.
4544 // FIXME: Need to calculate the composite type.
4545 // FIXME: Need to add qualifiers
4546
4547 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4548 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4549 return LHSTy;
4550}
4551
4552/// \brief Return the resulting type when the operands are both block pointers.
4553static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4554 ExprResult &LHS,
4555 ExprResult &RHS,
4556 SourceLocation Loc) {
4557 QualType LHSTy = LHS.get()->getType();
4558 QualType RHSTy = RHS.get()->getType();
4559
4560 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4561 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4562 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4563 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4564 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4565 return destType;
4566 }
4567 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4568 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4569 << RHS.get()->getSourceRange();
4570 return QualType();
4571 }
4572
4573 // We have 2 block pointer types.
4574 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4575}
4576
4577/// \brief Return the resulting type when the operands are both pointers.
4578static QualType
4579checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4580 ExprResult &RHS,
4581 SourceLocation Loc) {
4582 // get the pointer types
4583 QualType LHSTy = LHS.get()->getType();
4584 QualType RHSTy = RHS.get()->getType();
4585
4586 // get the "pointed to" types
4587 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4588 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4589
4590 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4591 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4592 // Figure out necessary qualifiers (C99 6.5.15p6)
4593 QualType destPointee
4594 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4595 QualType destType = S.Context.getPointerType(destPointee);
4596 // Add qualifiers if necessary.
4597 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4598 // Promote to void*.
4599 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4600 return destType;
4601 }
4602 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4603 QualType destPointee
4604 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4605 QualType destType = S.Context.getPointerType(destPointee);
4606 // Add qualifiers if necessary.
4607 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4608 // Promote to void*.
4609 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4610 return destType;
4611 }
4612
4613 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4614}
4615
4616/// \brief Return false if the first expression is not an integer and the second
4617/// expression is not a pointer, true otherwise.
4618static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4619 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004620 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00004621 if (!PointerExpr->getType()->isPointerType() ||
4622 !Int.get()->getType()->isIntegerType())
4623 return false;
4624
Richard Trieuccd891a2011-09-09 01:45:06 +00004625 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4626 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00004627
4628 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4629 << Expr1->getType() << Expr2->getType()
4630 << Expr1->getSourceRange() << Expr2->getSourceRange();
4631 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4632 CK_IntegralToPointer);
4633 return true;
4634}
4635
Richard Trieu33fc7572011-09-06 20:06:39 +00004636/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4637/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004638/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004639QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4640 ExprResult &RHS, ExprValueKind &VK,
4641 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004642 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004643
Richard Trieu33fc7572011-09-06 20:06:39 +00004644 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4645 if (!LHSResult.isUsable()) return QualType();
4646 LHS = move(LHSResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004647
Richard Trieu33fc7572011-09-06 20:06:39 +00004648 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4649 if (!RHSResult.isUsable()) return QualType();
4650 RHS = move(RHSResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004651
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004652 // C++ is sufficiently different to merit its own checker.
4653 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004654 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004655
4656 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004657 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004658
John Wiegley429bb272011-04-08 18:41:53 +00004659 Cond = UsualUnaryConversions(Cond.take());
4660 if (Cond.isInvalid())
4661 return QualType();
4662 LHS = UsualUnaryConversions(LHS.take());
4663 if (LHS.isInvalid())
4664 return QualType();
4665 RHS = UsualUnaryConversions(RHS.take());
4666 if (RHS.isInvalid())
4667 return QualType();
4668
4669 QualType CondTy = Cond.get()->getType();
4670 QualType LHSTy = LHS.get()->getType();
4671 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004672
Reid Spencer5f016e22007-07-11 17:01:13 +00004673 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00004674 if (checkCondition(*this, Cond.get()))
4675 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004676
Chris Lattner70d67a92008-01-06 22:42:25 +00004677 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004678 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004679 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004680
Nate Begeman6155d732010-09-20 22:41:17 +00004681 // OpenCL: If the condition is a vector, and both operands are scalar,
4682 // attempt to implicity convert them to the vector type to act like the
4683 // built in select.
Richard Trieu26f96072011-09-02 01:51:02 +00004684 if (getLangOptions().OpenCL && CondTy->isVectorType())
4685 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00004686 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00004687
Chris Lattner70d67a92008-01-06 22:42:25 +00004688 // If both operands have arithmetic type, do the usual arithmetic conversions
4689 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004690 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4691 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004692 if (LHS.isInvalid() || RHS.isInvalid())
4693 return QualType();
4694 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004695 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004696
Chris Lattner70d67a92008-01-06 22:42:25 +00004697 // If both operands are the same structure or union type, the result is that
4698 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004699 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4700 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004701 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004702 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004703 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004704 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004705 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004706 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004707
Chris Lattner70d67a92008-01-06 22:42:25 +00004708 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004709 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004710 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004711 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00004712 }
Richard Trieu26f96072011-09-02 01:51:02 +00004713
Steve Naroffb6d54e52008-01-08 01:11:38 +00004714 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4715 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00004716 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4717 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004718
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004719 // All objective-c pointer type analysis is done here.
4720 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4721 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00004722 if (LHS.isInvalid() || RHS.isInvalid())
4723 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004724 if (!compositeType.isNull())
4725 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004726
4727
Steve Naroff7154a772009-07-01 14:36:47 +00004728 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00004729 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4730 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4731 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004732
Steve Naroff7154a772009-07-01 14:36:47 +00004733 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00004734 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4735 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4736 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004737
John McCall404cd162010-11-13 01:35:44 +00004738 // GCC compatibility: soften pointer/integer mismatch. Note that
4739 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00004740 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4741 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00004742 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004743 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4744 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00004745 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004746
Chandler Carruth82214a82011-02-18 23:54:50 +00004747 // Emit a better diagnostic if one of the expressions is a null pointer
4748 // constant and the other is not a pointer type. In this case, the user most
4749 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00004750 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00004751 return QualType();
4752
Chris Lattner70d67a92008-01-06 22:42:25 +00004753 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004754 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00004755 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4756 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004757 return QualType();
4758}
4759
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004760/// FindCompositeObjCPointerType - Helper method to find composite type of
4761/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00004762QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00004763 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00004764 QualType LHSTy = LHS.get()->getType();
4765 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004766
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004767 // Handle things like Class and struct objc_class*. Here we case the result
4768 // to the pseudo-builtin, because that will be implicitly cast back to the
4769 // redefinition type if an attempt is made to access its fields.
4770 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004771 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004772 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004773 return LHSTy;
4774 }
4775 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004776 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004777 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004778 return RHSTy;
4779 }
4780 // And the same for struct objc_object* / id
4781 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004782 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004783 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004784 return LHSTy;
4785 }
4786 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004787 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004788 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004789 return RHSTy;
4790 }
4791 // And the same for struct objc_selector* / SEL
4792 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004793 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004794 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004795 return LHSTy;
4796 }
4797 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004798 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004799 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004800 return RHSTy;
4801 }
4802 // Check constraints for Objective-C object pointers types.
4803 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004804
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004805 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4806 // Two identical object pointer types are always compatible.
4807 return LHSTy;
4808 }
John McCall1d9b3b22011-09-09 05:25:32 +00004809 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4810 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004811 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004812
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004813 // If both operands are interfaces and either operand can be
4814 // assigned to the other, use that type as the composite
4815 // type. This allows
4816 // xxx ? (A*) a : (B*) b
4817 // where B is a subclass of A.
4818 //
4819 // Additionally, as for assignment, if either type is 'id'
4820 // allow silent coercion. Finally, if the types are
4821 // incompatible then make sure to use 'id' as the composite
4822 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004823
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004824 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4825 // It could return the composite type.
4826 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4827 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4828 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4829 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4830 } else if ((LHSTy->isObjCQualifiedIdType() ||
4831 RHSTy->isObjCQualifiedIdType()) &&
4832 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4833 // Need to handle "id<xx>" explicitly.
4834 // GCC allows qualified id and any Objective-C type to devolve to
4835 // id. Currently localizing to here until clear this should be
4836 // part of ObjCQualifiedIdTypesAreCompatible.
4837 compositeType = Context.getObjCIdType();
4838 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4839 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004840 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004841 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4842 ;
4843 else {
4844 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4845 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00004846 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004847 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00004848 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4849 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004850 return incompatTy;
4851 }
4852 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00004853 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4854 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004855 return compositeType;
4856 }
4857 // Check Objective-C object pointer types and 'void *'
4858 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4859 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4860 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4861 QualType destPointee
4862 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4863 QualType destType = Context.getPointerType(destPointee);
4864 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004865 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004866 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004867 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004868 return destType;
4869 }
4870 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4871 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4872 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4873 QualType destPointee
4874 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4875 QualType destType = Context.getPointerType(destPointee);
4876 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004877 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004878 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004879 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004880 return destType;
4881 }
4882 return QualType();
4883}
4884
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004885/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004886/// ParenRange in parentheses.
4887static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004888 const PartialDiagnostic &Note,
4889 SourceRange ParenRange) {
4890 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4891 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4892 EndLoc.isValid()) {
4893 Self.Diag(Loc, Note)
4894 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4895 << FixItHint::CreateInsertion(EndLoc, ")");
4896 } else {
4897 // We can't display the parentheses, so just show the bare note.
4898 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004899 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004900}
4901
4902static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4903 return Opc >= BO_Mul && Opc <= BO_Shr;
4904}
4905
Hans Wennborg2f072b42011-06-09 17:06:51 +00004906/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4907/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00004908/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
4909/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00004910static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00004911 Expr **RHSExprs) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00004912 E = E->IgnoreParenImpCasts();
4913 E = E->IgnoreConversionOperator();
4914 E = E->IgnoreParenImpCasts();
4915
4916 // Built-in binary operator.
4917 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4918 if (IsArithmeticOp(OP->getOpcode())) {
4919 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00004920 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00004921 return true;
4922 }
4923 }
4924
4925 // Overloaded operator.
4926 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4927 if (Call->getNumArgs() != 2)
4928 return false;
4929
4930 // Make sure this is really a binary operator that is safe to pass into
4931 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4932 OverloadedOperatorKind OO = Call->getOperator();
4933 if (OO < OO_Plus || OO > OO_Arrow)
4934 return false;
4935
4936 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4937 if (IsArithmeticOp(OpKind)) {
4938 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00004939 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00004940 return true;
4941 }
4942 }
4943
4944 return false;
4945}
4946
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004947static bool IsLogicOp(BinaryOperatorKind Opc) {
4948 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4949}
4950
Hans Wennborg2f072b42011-06-09 17:06:51 +00004951/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4952/// or is a logical expression such as (x==y) which has int type, but is
4953/// commonly interpreted as boolean.
4954static bool ExprLooksBoolean(Expr *E) {
4955 E = E->IgnoreParenImpCasts();
4956
4957 if (E->getType()->isBooleanType())
4958 return true;
4959 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4960 return IsLogicOp(OP->getOpcode());
4961 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4962 return OP->getOpcode() == UO_LNot;
4963
4964 return false;
4965}
4966
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004967/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4968/// and binary operator are mixed in a way that suggests the programmer assumed
4969/// the conditional operator has higher precedence, for example:
4970/// "int x = a + someBinaryCondition ? 1 : 2".
4971static void DiagnoseConditionalPrecedence(Sema &Self,
4972 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004973 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00004974 Expr *LHSExpr,
4975 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00004976 BinaryOperatorKind CondOpcode;
4977 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004978
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004979 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00004980 return;
4981 if (!ExprLooksBoolean(CondRHS))
4982 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004983
Hans Wennborg2f072b42011-06-09 17:06:51 +00004984 // The condition is an arithmetic binary expression, with a right-
4985 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004986
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004987 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004988 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00004989 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004990
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004991 SuggestParentheses(Self, OpLoc,
4992 Self.PDiag(diag::note_precedence_conditional_silence)
4993 << BinaryOperator::getOpcodeStr(CondOpcode),
4994 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00004995
4996 SuggestParentheses(Self, OpLoc,
4997 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00004998 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004999}
5000
Steve Narofff69936d2007-09-16 03:34:24 +00005001/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005002/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005003ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005004 SourceLocation ColonLoc,
5005 Expr *CondExpr, Expr *LHSExpr,
5006 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005007 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5008 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005009 OpaqueValueExpr *opaqueValue = 0;
5010 Expr *commonExpr = 0;
5011 if (LHSExpr == 0) {
5012 commonExpr = CondExpr;
5013
5014 // We usually want to apply unary conversions *before* saving, except
5015 // in the special case of a C++ l-value conditional.
5016 if (!(getLangOptions().CPlusPlus
5017 && !commonExpr->isTypeDependent()
5018 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5019 && commonExpr->isGLValue()
5020 && commonExpr->isOrdinaryOrBitFieldObject()
5021 && RHSExpr->isOrdinaryOrBitFieldObject()
5022 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005023 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5024 if (commonRes.isInvalid())
5025 return ExprError();
5026 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005027 }
5028
5029 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5030 commonExpr->getType(),
5031 commonExpr->getValueKind(),
5032 commonExpr->getObjectKind());
5033 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005034 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005035
John McCallf89e55a2010-11-18 06:31:45 +00005036 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005037 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005038 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5039 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005040 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005041 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5042 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005043 return ExprError();
5044
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005045 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5046 RHS.get());
5047
John McCall56ca35d2011-02-17 10:25:35 +00005048 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005049 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5050 LHS.take(), ColonLoc,
5051 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005052
5053 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005054 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005055 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5056 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005057}
5058
John McCalle4be87e2011-01-31 23:13:11 +00005059// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005060// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005061// routine is it effectively iqnores the qualifiers on the top level pointee.
5062// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5063// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005064static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005065checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5066 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5067 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005068
Reid Spencer5f016e22007-07-11 17:01:13 +00005069 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005070 const Type *lhptee, *rhptee;
5071 Qualifiers lhq, rhq;
Richard Trieu1da27a12011-09-06 20:21:22 +00005072 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5073 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005074
John McCalle4be87e2011-01-31 23:13:11 +00005075 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005076
5077 // C99 6.5.16.1p1: This following citation is common to constraints
5078 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5079 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005080 Qualifiers lq;
5081
John McCallf85e1932011-06-15 23:02:42 +00005082 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5083 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5084 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5085 // Ignore lifetime for further calculation.
5086 lhq.removeObjCLifetime();
5087 rhq.removeObjCLifetime();
5088 }
5089
John McCall86c05f32011-02-01 00:10:29 +00005090 if (!lhq.compatiblyIncludes(rhq)) {
5091 // Treat address-space mismatches as fatal. TODO: address subspaces
5092 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5093 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5094
John McCallf85e1932011-06-15 23:02:42 +00005095 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005096 // and from void*.
John McCallf85e1932011-06-15 23:02:42 +00005097 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5098 .compatiblyIncludes(
5099 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall22348732011-03-26 02:56:45 +00005100 && (lhptee->isVoidType() || rhptee->isVoidType()))
5101 ; // keep old
5102
John McCallf85e1932011-06-15 23:02:42 +00005103 // Treat lifetime mismatches as fatal.
5104 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5105 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5106
John McCall86c05f32011-02-01 00:10:29 +00005107 // For GCC compatibility, other qualifier mismatches are treated
5108 // as still compatible in C.
5109 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5110 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005111
Mike Stumpeed9cac2009-02-19 03:04:26 +00005112 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5113 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005114 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005115 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005116 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005117 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005118
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005119 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005120 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005121 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005122 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005123
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005124 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005125 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005126 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005127
5128 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005129 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005130 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005131 }
John McCall86c05f32011-02-01 00:10:29 +00005132
Mike Stumpeed9cac2009-02-19 03:04:26 +00005133 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005134 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005135 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5136 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005137 // Check if the pointee types are compatible ignoring the sign.
5138 // We explicitly check for char so that we catch "char" vs
5139 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005140 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005141 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005142 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005143 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005144
Chris Lattner6a2b9262009-10-17 20:33:28 +00005145 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005146 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005147 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005148 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005149
John McCall86c05f32011-02-01 00:10:29 +00005150 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005151 // Types are compatible ignoring the sign. Qualifier incompatibility
5152 // takes priority over sign incompatibility because the sign
5153 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005154 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005155 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005156
John McCalle4be87e2011-01-31 23:13:11 +00005157 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005158 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005159
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005160 // If we are a multi-level pointer, it's possible that our issue is simply
5161 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5162 // the eventual target type is the same and the pointers have the same
5163 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005164 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005165 do {
John McCall86c05f32011-02-01 00:10:29 +00005166 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5167 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005168 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005169
John McCall86c05f32011-02-01 00:10:29 +00005170 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005171 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005172 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005173
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005174 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005175 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005176 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005177 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005178}
5179
John McCalle4be87e2011-01-31 23:13:11 +00005180/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005181/// block pointer types are compatible or whether a block and normal pointer
5182/// are compatible. It is more restrict than comparing two function pointer
5183// types.
John McCalle4be87e2011-01-31 23:13:11 +00005184static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005185checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5186 QualType RHSType) {
5187 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5188 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005189
Steve Naroff1c7d0672008-09-04 15:10:53 +00005190 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005191
Steve Naroff1c7d0672008-09-04 15:10:53 +00005192 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00005193 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5194 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005195
John McCalle4be87e2011-01-31 23:13:11 +00005196 // In C++, the types have to match exactly.
5197 if (S.getLangOptions().CPlusPlus)
5198 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005199
John McCalle4be87e2011-01-31 23:13:11 +00005200 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005201
Steve Naroff1c7d0672008-09-04 15:10:53 +00005202 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005203 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5204 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005205
Richard Trieu1da27a12011-09-06 20:21:22 +00005206 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005207 return Sema::IncompatibleBlockPointer;
5208
Steve Naroff1c7d0672008-09-04 15:10:53 +00005209 return ConvTy;
5210}
5211
John McCalle4be87e2011-01-31 23:13:11 +00005212/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005213/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005214static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005215checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5216 QualType RHSType) {
5217 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5218 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005219
Richard Trieu1da27a12011-09-06 20:21:22 +00005220 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005221 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005222 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5223 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005224 return Sema::IncompatiblePointer;
5225 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005226 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005227 if (RHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005228 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005229 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5230 !LHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005231 return Sema::IncompatiblePointer;
5232 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005233 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005234 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5235 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005236
John McCalle4be87e2011-01-31 23:13:11 +00005237 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5238 return Sema::CompatiblePointerDiscardsQualifiers;
5239
Richard Trieu1da27a12011-09-06 20:21:22 +00005240 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005241 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00005242 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005243 return Sema::IncompatibleObjCQualifiedId;
5244 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005245}
5246
John McCall1c23e912010-11-16 02:32:08 +00005247Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005248Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00005249 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00005250 // Fake up an opaque expression. We don't actually care about what
5251 // cast operations are required, so if CheckAssignmentConstraints
5252 // adds casts to this they'll be wasted, but fortunately that doesn't
5253 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00005254 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5255 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00005256 CastKind K = CK_Invalid;
5257
Richard Trieu1da27a12011-09-06 20:21:22 +00005258 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00005259}
5260
Mike Stumpeed9cac2009-02-19 03:04:26 +00005261/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5262/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005263/// pointers. Here are some objectionable examples that GCC considers warnings:
5264///
5265/// int a, *pint;
5266/// short *pshort;
5267/// struct foo *pfoo;
5268///
5269/// pint = pshort; // warning: assignment from incompatible pointer type
5270/// a = pint; // warning: assignment makes integer from pointer without a cast
5271/// pint = a; // warning: assignment makes pointer from integer without a cast
5272/// pint = pfoo; // warning: assignment from incompatible pointer type
5273///
5274/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005275/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005276///
John McCalldaa8e4e2010-11-15 09:13:47 +00005277/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005278Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00005279Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00005280 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00005281 QualType RHSType = RHS.get()->getType();
5282 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00005283
Chris Lattnerfc144e22008-01-04 23:18:45 +00005284 // Get canonical types. We're not formatting these types, just comparing
5285 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00005286 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5287 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005288
John McCallb6cfa242011-01-31 22:28:28 +00005289 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00005290 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005291 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005292 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005293 }
5294
Douglas Gregor9d293df2008-10-28 00:22:11 +00005295 // If the left-hand side is a reference type, then we are in a
5296 // (rare!) case where we've allowed the use of references in C,
5297 // e.g., as a parameter type in a built-in function. In this case,
5298 // just make sure that the type referenced is compatible with the
5299 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00005300 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00005301 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005302 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5303 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005304 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005305 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005306 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005307 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005308 }
John McCallb6cfa242011-01-31 22:28:28 +00005309
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005310 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5311 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005312 if (LHSType->isExtVectorType()) {
5313 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005314 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00005315 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005316 // CK_VectorSplat does T -> vector T, so first cast to the
5317 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005318 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5319 if (elType != RHSType) {
5320 Kind = PrepareScalarCast(*this, RHS, elType);
5321 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005322 }
5323 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005324 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005325 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005326 }
Mike Stump1eb44332009-09-09 15:08:12 +00005327
John McCallb6cfa242011-01-31 22:28:28 +00005328 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005329 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5330 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005331 // Allow assignments of an AltiVec vector type to an equivalent GCC
5332 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00005333 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005334 Kind = CK_BitCast;
5335 return Compatible;
5336 }
5337
Douglas Gregor255210e2010-08-06 10:14:59 +00005338 // If we are allowing lax vector conversions, and LHS and RHS are both
5339 // vectors, the total size only needs to be the same. This is a bitcast;
5340 // no bits are changed but the result type is different.
5341 if (getLangOptions().LaxVectorConversions &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005342 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005343 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005344 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005345 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005346 }
5347 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005348 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005349
John McCallb6cfa242011-01-31 22:28:28 +00005350 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00005351 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5352 !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
5353 Kind = PrepareScalarCast(*this, RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005354 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005355 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005356
John McCallb6cfa242011-01-31 22:28:28 +00005357 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005358 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005359 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005360 if (isa<PointerType>(RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005361 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005362 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005363 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005364
John McCallb6cfa242011-01-31 22:28:28 +00005365 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005366 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005367 Kind = CK_IntegralToPointer; // FIXME: null?
5368 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005369 }
John McCallb6cfa242011-01-31 22:28:28 +00005370
5371 // C pointers are not compatible with ObjC object pointers,
5372 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005373 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005374 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005375 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005376 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00005377 return Compatible;
5378 }
5379
5380 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005381 if (RHSType->isObjCClassType() &&
5382 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005383 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005384 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005385 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005386 }
Steve Naroffb4406862008-09-29 18:10:17 +00005387
John McCallb6cfa242011-01-31 22:28:28 +00005388 Kind = CK_BitCast;
5389 return IncompatiblePointer;
5390 }
5391
5392 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005393 if (RHSType->getAs<BlockPointerType>()) {
5394 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005395 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005396 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005397 }
Steve Naroffb4406862008-09-29 18:10:17 +00005398 }
John McCallb6cfa242011-01-31 22:28:28 +00005399
Steve Naroff1c7d0672008-09-04 15:10:53 +00005400 return Incompatible;
5401 }
5402
John McCallb6cfa242011-01-31 22:28:28 +00005403 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005404 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005405 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005406 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005407 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005408 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00005409 }
5410
5411 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005412 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005413 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005414 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005415 }
5416
John McCallb6cfa242011-01-31 22:28:28 +00005417 // id -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005418 if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005419 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005420 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005421 }
Steve Naroffb4406862008-09-29 18:10:17 +00005422
John McCallb6cfa242011-01-31 22:28:28 +00005423 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005424 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005425 if (RHSPT->getPointeeType()->isVoidType()) {
5426 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005427 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005428 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005429
Chris Lattnerfc144e22008-01-04 23:18:45 +00005430 return Incompatible;
5431 }
5432
John McCallb6cfa242011-01-31 22:28:28 +00005433 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005434 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005435 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00005436 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005437 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005438 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00005439 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005440 if (getLangOptions().ObjCAutoRefCount &&
5441 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005442 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005443 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005444 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005445 }
5446
5447 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005448 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005449 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005450 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005451 }
5452
John McCallb6cfa242011-01-31 22:28:28 +00005453 // In general, C pointers are not compatible with ObjC object pointers,
5454 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005455 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00005456 Kind = CK_CPointerToObjCPointerCast;
5457
John McCallb6cfa242011-01-31 22:28:28 +00005458 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00005459 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005460 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005461 }
5462
5463 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005464 if (LHSType->isObjCClassType() &&
5465 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005466 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005467 return Compatible;
5468 }
5469
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005470 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005471 }
John McCallb6cfa242011-01-31 22:28:28 +00005472
5473 // T^ -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005474 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005475 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005476 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005477 }
5478
Steve Naroff14108da2009-07-10 23:34:53 +00005479 return Incompatible;
5480 }
John McCallb6cfa242011-01-31 22:28:28 +00005481
5482 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005483 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005484 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005485 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005486 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005487 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005488 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005489
John McCallb6cfa242011-01-31 22:28:28 +00005490 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005491 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005492 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005493 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005494 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005495
Chris Lattnerfc144e22008-01-04 23:18:45 +00005496 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005497 }
John McCallb6cfa242011-01-31 22:28:28 +00005498
5499 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005500 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005501 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005502 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005503 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005504 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005505 }
Steve Naroff14108da2009-07-10 23:34:53 +00005506
John McCallb6cfa242011-01-31 22:28:28 +00005507 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005508 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005509 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005510 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005511 }
5512
Steve Naroff14108da2009-07-10 23:34:53 +00005513 return Incompatible;
5514 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005515
John McCallb6cfa242011-01-31 22:28:28 +00005516 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00005517 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5518 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005519 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005520 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005521 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005522 }
John McCallb6cfa242011-01-31 22:28:28 +00005523
Reid Spencer5f016e22007-07-11 17:01:13 +00005524 return Incompatible;
5525}
5526
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005527/// \brief Constructs a transparent union from an expression that is
5528/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005529static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5530 ExprResult &EResult, QualType UnionType,
5531 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005532 // Build an initializer list that designates the appropriate member
5533 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005534 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005535 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00005536 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005537 SourceLocation());
5538 Initializer->setType(UnionType);
5539 Initializer->setInitializedFieldInUnion(Field);
5540
5541 // Build a compound literal constructing a value of the transparent
5542 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005543 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005544 EResult = S.Owned(
5545 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5546 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005547}
5548
5549Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005550Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00005551 ExprResult &RHS) {
5552 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005553
Mike Stump1eb44332009-09-09 15:08:12 +00005554 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005555 // transparent_union GCC extension.
5556 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005557 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005558 return Incompatible;
5559
5560 // The field to initialize within the transparent union.
5561 RecordDecl *UD = UT->getDecl();
5562 FieldDecl *InitField = 0;
5563 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005564 for (RecordDecl::field_iterator it = UD->field_begin(),
5565 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005566 it != itend; ++it) {
5567 if (it->getType()->isPointerType()) {
5568 // If the transparent union contains a pointer type, we allow:
5569 // 1) void pointer
5570 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00005571 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00005572 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005573 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005574 InitField = *it;
5575 break;
5576 }
Mike Stump1eb44332009-09-09 15:08:12 +00005577
Richard Trieuf7720da2011-09-06 20:40:12 +00005578 if (RHS.get()->isNullPointerConstant(Context,
5579 Expr::NPC_ValueDependentIsNull)) {
5580 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5581 CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005582 InitField = *it;
5583 break;
5584 }
5585 }
5586
John McCalldaa8e4e2010-11-15 09:13:47 +00005587 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00005588 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005589 == Compatible) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005590 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005591 InitField = *it;
5592 break;
5593 }
5594 }
5595
5596 if (!InitField)
5597 return Incompatible;
5598
Richard Trieuf7720da2011-09-06 20:40:12 +00005599 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005600 return Compatible;
5601}
5602
Chris Lattner5cf216b2008-01-04 18:04:52 +00005603Sema::AssignConvertType
Richard Trieuf7720da2011-09-06 20:40:12 +00005604Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005605 if (getLangOptions().CPlusPlus) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005606 if (!LHSType->isRecordType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005607 // C++ 5.17p3: If the left operand is not of class type, the
5608 // expression is implicitly converted (C++ 4) to the
5609 // cv-unqualified type of the left operand.
Richard Trieuf7720da2011-09-06 20:40:12 +00005610 ExprResult Res = PerformImplicitConversion(RHS.get(),
5611 LHSType.getUnqualifiedType(),
John Wiegley429bb272011-04-08 18:41:53 +00005612 AA_Assigning);
5613 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005614 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005615 Sema::AssignConvertType result = Compatible;
5616 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00005617 !CheckObjCARCUnavailableWeakConversion(LHSType,
5618 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005619 result = IncompatibleObjCWeakRef;
Richard Trieuf7720da2011-09-06 20:40:12 +00005620 RHS = move(Res);
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005621 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005622 }
5623
5624 // FIXME: Currently, we fall through and treat C++ classes like C
5625 // structures.
John McCallf6a16482010-12-04 03:47:34 +00005626 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005627
Steve Naroff529a4ad2007-11-27 17:58:44 +00005628 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5629 // a null pointer constant.
Richard Trieuf7720da2011-09-06 20:40:12 +00005630 if ((LHSType->isPointerType() ||
5631 LHSType->isObjCObjectPointerType() ||
5632 LHSType->isBlockPointerType())
5633 && RHS.get()->isNullPointerConstant(Context,
5634 Expr::NPC_ValueDependentIsNull)) {
5635 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005636 return Compatible;
5637 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005638
Chris Lattner943140e2007-10-16 02:55:40 +00005639 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005640 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005641 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005642 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005643 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005644 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00005645 if (!LHSType->isReferenceType()) {
5646 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5647 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005648 return Incompatible;
5649 }
Steve Narofff1120de2007-08-24 22:33:52 +00005650
John McCalldaa8e4e2010-11-15 09:13:47 +00005651 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005652 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00005653 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005654
Steve Narofff1120de2007-08-24 22:33:52 +00005655 // C99 6.5.16.1p2: The value of the right operand is converted to the
5656 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00005657 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5658 // so that we can use references in built-in functions even in C.
5659 // The getNonReferenceType() call makes sure that the resulting expression
5660 // does not have reference type.
Richard Trieuf7720da2011-09-06 20:40:12 +00005661 if (result != Incompatible && RHS.get()->getType() != LHSType)
5662 RHS = ImpCastExprToType(RHS.take(),
5663 LHSType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00005664 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00005665}
5666
Richard Trieuf7720da2011-09-06 20:40:12 +00005667QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5668 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005669 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00005670 << LHS.get()->getType() << RHS.get()->getType()
5671 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00005672 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005673}
5674
Richard Trieu08062aa2011-09-06 21:01:04 +00005675QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00005676 SourceLocation Loc, bool IsCompAssign) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00005677 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005678 // For example, "const float" and "float" are equivalent.
Richard Trieu08062aa2011-09-06 21:01:04 +00005679 QualType LHSType =
5680 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5681 QualType RHSType =
5682 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005683
Nate Begemanbe2341d2008-07-14 18:02:46 +00005684 // If the vector types are identical, return.
Richard Trieu08062aa2011-09-06 21:01:04 +00005685 if (LHSType == RHSType)
5686 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00005687
Douglas Gregor255210e2010-08-06 10:14:59 +00005688 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu08062aa2011-09-06 21:01:04 +00005689 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5690 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5691 if (LHSType->isExtVectorType()) {
5692 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5693 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005694 }
5695
Richard Trieuccd891a2011-09-09 01:45:06 +00005696 if (!IsCompAssign)
Richard Trieu08062aa2011-09-06 21:01:04 +00005697 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5698 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00005699 }
5700
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005701 if (getLangOptions().LaxVectorConversions &&
Richard Trieu08062aa2011-09-06 21:01:04 +00005702 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005703 // If we are allowing lax vector conversions, and LHS and RHS are both
5704 // vectors, the total size only needs to be the same. This is a
5705 // bitcast; no bits are changed but the result type is different.
5706 // FIXME: Should we really be allowing this?
Richard Trieu08062aa2011-09-06 21:01:04 +00005707 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5708 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005709 }
5710
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005711 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5712 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5713 bool swapped = false;
Richard Trieuccd891a2011-09-09 01:45:06 +00005714 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005715 swapped = true;
Richard Trieu08062aa2011-09-06 21:01:04 +00005716 std::swap(RHS, LHS);
5717 std::swap(RHSType, LHSType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005718 }
Mike Stump1eb44332009-09-09 15:08:12 +00005719
Nate Begemandde25982009-06-28 19:12:57 +00005720 // Handle the case of an ext vector and scalar.
Richard Trieu08062aa2011-09-06 21:01:04 +00005721 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005722 QualType EltTy = LV->getElementType();
Richard Trieu08062aa2011-09-06 21:01:04 +00005723 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5724 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005725 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00005726 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005727 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00005728 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5729 if (swapped) std::swap(RHS, LHS);
5730 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005731 }
5732 }
Richard Trieu08062aa2011-09-06 21:01:04 +00005733 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5734 RHSType->isRealFloatingType()) {
5735 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005736 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00005737 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005738 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00005739 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5740 if (swapped) std::swap(RHS, LHS);
5741 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005742 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00005743 }
5744 }
Mike Stump1eb44332009-09-09 15:08:12 +00005745
Nate Begemandde25982009-06-28 19:12:57 +00005746 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu08062aa2011-09-06 21:01:04 +00005747 if (swapped) std::swap(RHS, LHS);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005748 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu08062aa2011-09-06 21:01:04 +00005749 << LHS.get()->getType() << RHS.get()->getType()
5750 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005751 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00005752}
5753
Richard Trieu08062aa2011-09-06 21:01:04 +00005754QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00005755 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00005756 bool IsCompAssign, bool IsDiv) {
Richard Trieu08062aa2011-09-06 21:01:04 +00005757 if (LHS.get()->getType()->isVectorType() ||
5758 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00005759 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005760
Richard Trieuccd891a2011-09-09 01:45:06 +00005761 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00005762 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005763 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005764
Richard Trieu08062aa2011-09-06 21:01:04 +00005765 if (!LHS.get()->getType()->isArithmeticType() ||
5766 !RHS.get()->getType()->isArithmeticType())
5767 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005768
Chris Lattner7ef655a2010-01-12 21:23:57 +00005769 // Check for division by zero.
Richard Trieuccd891a2011-09-09 01:45:06 +00005770 if (IsDiv &&
Richard Trieu08062aa2011-09-06 21:01:04 +00005771 RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00005772 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00005773 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5774 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005775
Chris Lattner7ef655a2010-01-12 21:23:57 +00005776 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005777}
5778
Chris Lattner7ef655a2010-01-12 21:23:57 +00005779QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00005780 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu08062aa2011-09-06 21:01:04 +00005781 if (LHS.get()->getType()->isVectorType() ||
5782 RHS.get()->getType()->isVectorType()) {
5783 if (LHS.get()->getType()->hasIntegerRepresentation() &&
5784 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00005785 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00005786 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00005787 }
Steve Naroff90045e82007-07-13 23:32:42 +00005788
Richard Trieuccd891a2011-09-09 01:45:06 +00005789 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00005790 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005791 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005792
Richard Trieu08062aa2011-09-06 21:01:04 +00005793 if (!LHS.get()->getType()->isIntegerType() ||
5794 !RHS.get()->getType()->isIntegerType())
5795 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005796
Chris Lattner7ef655a2010-01-12 21:23:57 +00005797 // Check for remainder by zero.
Richard Trieu08062aa2011-09-06 21:01:04 +00005798 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00005799 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00005800 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5801 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005802
Chris Lattner7ef655a2010-01-12 21:23:57 +00005803 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005804}
5805
Chandler Carruth13b21be2011-06-27 08:02:19 +00005806/// \brief Diagnose invalid arithmetic on two void pointers.
5807static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00005808 Expr *LHSExpr, Expr *RHSExpr) {
Chandler Carruth13b21be2011-06-27 08:02:19 +00005809 S.Diag(Loc, S.getLangOptions().CPlusPlus
5810 ? diag::err_typecheck_pointer_arith_void_type
5811 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00005812 << 1 /* two pointers */ << LHSExpr->getSourceRange()
5813 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00005814}
5815
5816/// \brief Diagnose invalid arithmetic on a void pointer.
5817static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5818 Expr *Pointer) {
5819 S.Diag(Loc, S.getLangOptions().CPlusPlus
5820 ? diag::err_typecheck_pointer_arith_void_type
5821 : diag::ext_gnu_void_ptr)
5822 << 0 /* one pointer */ << Pointer->getSourceRange();
5823}
5824
5825/// \brief Diagnose invalid arithmetic on two function pointers.
5826static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5827 Expr *LHS, Expr *RHS) {
5828 assert(LHS->getType()->isAnyPointerType());
5829 assert(RHS->getType()->isAnyPointerType());
5830 S.Diag(Loc, S.getLangOptions().CPlusPlus
5831 ? diag::err_typecheck_pointer_arith_function_type
5832 : diag::ext_gnu_ptr_func_arith)
5833 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5834 // We only show the second type if it differs from the first.
5835 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5836 RHS->getType())
5837 << RHS->getType()->getPointeeType()
5838 << LHS->getSourceRange() << RHS->getSourceRange();
5839}
5840
5841/// \brief Diagnose invalid arithmetic on a function pointer.
5842static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5843 Expr *Pointer) {
5844 assert(Pointer->getType()->isAnyPointerType());
5845 S.Diag(Loc, S.getLangOptions().CPlusPlus
5846 ? diag::err_typecheck_pointer_arith_function_type
5847 : diag::ext_gnu_ptr_func_arith)
5848 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5849 << 0 /* one pointer, so only one type */
5850 << Pointer->getSourceRange();
5851}
5852
Richard Trieu097ecd22011-09-02 02:15:37 +00005853/// \brief Warn if Operand is incomplete pointer type
5854///
5855/// \returns True if pointer has incomplete type
5856static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
5857 Expr *Operand) {
5858 if ((Operand->getType()->isPointerType() &&
5859 !Operand->getType()->isDependentType()) ||
5860 Operand->getType()->isObjCObjectPointerType()) {
5861 QualType PointeeTy = Operand->getType()->getPointeeType();
5862 if (S.RequireCompleteType(
5863 Loc, PointeeTy,
5864 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5865 << PointeeTy << Operand->getSourceRange()))
5866 return true;
5867 }
5868 return false;
5869}
5870
Chandler Carruth13b21be2011-06-27 08:02:19 +00005871/// \brief Check the validity of an arithmetic pointer operand.
5872///
5873/// If the operand has pointer type, this code will check for pointer types
5874/// which are invalid in arithmetic operations. These will be diagnosed
5875/// appropriately, including whether or not the use is supported as an
5876/// extension.
5877///
5878/// \returns True when the operand is valid to use (even if as an extension).
5879static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5880 Expr *Operand) {
5881 if (!Operand->getType()->isAnyPointerType()) return true;
5882
5883 QualType PointeeTy = Operand->getType()->getPointeeType();
5884 if (PointeeTy->isVoidType()) {
5885 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5886 return !S.getLangOptions().CPlusPlus;
5887 }
5888 if (PointeeTy->isFunctionType()) {
5889 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5890 return !S.getLangOptions().CPlusPlus;
5891 }
5892
Richard Trieu097ecd22011-09-02 02:15:37 +00005893 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00005894
5895 return true;
5896}
5897
5898/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5899/// operands.
5900///
5901/// This routine will diagnose any invalid arithmetic on pointer operands much
5902/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5903/// for emitting a single diagnostic even for operations where both LHS and RHS
5904/// are (potentially problematic) pointers.
5905///
5906/// \returns True when the operand is valid to use (even if as an extension).
5907static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00005908 Expr *LHSExpr, Expr *RHSExpr) {
5909 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
5910 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00005911 if (!isLHSPointer && !isRHSPointer) return true;
5912
5913 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00005914 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
5915 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00005916
5917 // Check for arithmetic on pointers to incomplete types.
5918 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5919 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
5920 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00005921 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
5922 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
5923 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00005924
5925 return !S.getLangOptions().CPlusPlus;
5926 }
5927
5928 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
5929 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
5930 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00005931 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
5932 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
5933 RHSExpr);
5934 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00005935
5936 return !S.getLangOptions().CPlusPlus;
5937 }
5938
Richard Trieudef75842011-09-06 21:13:51 +00005939 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
5940 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00005941
Chandler Carruth13b21be2011-06-27 08:02:19 +00005942 return true;
5943}
5944
Richard Trieudb44a6b2011-09-01 22:53:23 +00005945/// \brief Check bad cases where we step over interface counts.
5946static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
5947 SourceLocation OpLoc,
5948 Expr *Op) {
5949 assert(Op->getType()->isAnyPointerType());
5950 QualType PointeeTy = Op->getType()->getPointeeType();
5951 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
5952 return true;
5953
5954 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5955 << PointeeTy << Op->getSourceRange();
5956 return false;
5957}
5958
5959/// \brief Warn when two pointers are incompatible.
5960static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00005961 Expr *LHSExpr, Expr *RHSExpr) {
5962 assert(LHSExpr->getType()->isAnyPointerType());
5963 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00005964 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00005965 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
5966 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00005967}
5968
Chris Lattner7ef655a2010-01-12 21:23:57 +00005969QualType Sema::CheckAdditionOperands( // C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00005970 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy) {
5971 if (LHS.get()->getType()->isVectorType() ||
5972 RHS.get()->getType()->isVectorType()) {
5973 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00005974 if (CompLHSTy) *CompLHSTy = compType;
5975 return compType;
5976 }
Steve Naroff49b45262007-07-13 16:58:59 +00005977
Richard Trieudef75842011-09-06 21:13:51 +00005978 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
5979 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005980 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00005981
Reid Spencer5f016e22007-07-11 17:01:13 +00005982 // handle the common case first (both operands are arithmetic).
Richard Trieudef75842011-09-06 21:13:51 +00005983 if (LHS.get()->getType()->isArithmeticType() &&
5984 RHS.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005985 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005986 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005987 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005988
Eli Friedmand72d16e2008-05-18 18:08:51 +00005989 // Put any potential pointer into PExp
Richard Trieudef75842011-09-06 21:13:51 +00005990 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005991 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00005992 std::swap(PExp, IExp);
5993
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005994 if (PExp->getType()->isAnyPointerType()) {
Eli Friedmand72d16e2008-05-18 18:08:51 +00005995 if (IExp->getType()->isIntegerType()) {
Chandler Carruth13b21be2011-06-27 08:02:19 +00005996 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
5997 return QualType();
5998
Chris Lattnerb5f15622009-04-24 23:50:08 +00005999 // Diagnose bad cases where we step over interface counts.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006000 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006001 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006002
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006003 // Check array bounds for pointer arithemtic
6004 CheckArrayAccess(PExp, IExp);
6005
Eli Friedmanab3a8522009-03-28 01:22:36 +00006006 if (CompLHSTy) {
Richard Trieudef75842011-09-06 21:13:51 +00006007 QualType LHSTy = Context.isPromotableBitField(LHS.get());
Eli Friedman04e83572009-08-20 04:21:42 +00006008 if (LHSTy.isNull()) {
Richard Trieudef75842011-09-06 21:13:51 +00006009 LHSTy = LHS.get()->getType();
Eli Friedman04e83572009-08-20 04:21:42 +00006010 if (LHSTy->isPromotableIntegerType())
6011 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00006012 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00006013 *CompLHSTy = LHSTy;
6014 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00006015 return PExp->getType();
6016 }
6017 }
6018
Richard Trieudef75842011-09-06 21:13:51 +00006019 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006020}
6021
Chris Lattnereca7be62008-04-07 05:30:13 +00006022// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006023QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006024 SourceLocation Loc,
6025 QualType* CompLHSTy) {
Richard Trieudef75842011-09-06 21:13:51 +00006026 if (LHS.get()->getType()->isVectorType() ||
6027 RHS.get()->getType()->isVectorType()) {
6028 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006029 if (CompLHSTy) *CompLHSTy = compType;
6030 return compType;
6031 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006032
Richard Trieudef75842011-09-06 21:13:51 +00006033 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6034 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006035 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006036
Chris Lattner6e4ab612007-12-09 21:53:25 +00006037 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006038
Chris Lattner6e4ab612007-12-09 21:53:25 +00006039 // Handle the common case first (both operands are arithmetic).
Richard Trieudef75842011-09-06 21:13:51 +00006040 if (LHS.get()->getType()->isArithmeticType() &&
6041 RHS.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006042 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006043 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006044 }
Mike Stump1eb44332009-09-09 15:08:12 +00006045
Chris Lattner6e4ab612007-12-09 21:53:25 +00006046 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00006047 if (LHS.get()->getType()->isAnyPointerType()) {
6048 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006049
Chris Lattnerb5f15622009-04-24 23:50:08 +00006050 // Diagnose bad cases where we step over interface counts.
Richard Trieudef75842011-09-06 21:13:51 +00006051 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006052 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006053
Chris Lattner6e4ab612007-12-09 21:53:25 +00006054 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00006055 if (RHS.get()->getType()->isIntegerType()) {
6056 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006057 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006058
Richard Trieudef75842011-09-06 21:13:51 +00006059 Expr *IExpr = RHS.get()->IgnoreParenCasts();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006060 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6061 OK_Ordinary, IExpr->getExprLoc());
6062 // Check array bounds for pointer arithemtic
Richard Trieudef75842011-09-06 21:13:51 +00006063 CheckArrayAccess(LHS.get()->IgnoreParenCasts(), &negRex);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006064
Richard Trieudef75842011-09-06 21:13:51 +00006065 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6066 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006067 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006068
Chris Lattner6e4ab612007-12-09 21:53:25 +00006069 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006070 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00006071 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006072 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006073
Eli Friedman88d936b2009-05-16 13:54:38 +00006074 if (getLangOptions().CPlusPlus) {
6075 // Pointee types must be the same: C++ [expr.add]
6076 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00006077 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006078 }
6079 } else {
6080 // Pointee types must be compatible C99 6.5.6p3
6081 if (!Context.typesAreCompatible(
6082 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6083 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00006084 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006085 return QualType();
6086 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006087 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006088
Chandler Carruth13b21be2011-06-27 08:02:19 +00006089 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006090 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006091 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006092
Richard Trieudef75842011-09-06 21:13:51 +00006093 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006094 return Context.getPointerDiffType();
6095 }
6096 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006097
Richard Trieudef75842011-09-06 21:13:51 +00006098 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006099}
6100
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006101static bool isScopedEnumerationType(QualType T) {
6102 if (const EnumType *ET = dyn_cast<EnumType>(T))
6103 return ET->getDecl()->isScoped();
6104 return false;
6105}
6106
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006107static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00006108 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006109 QualType LHSType) {
Chandler Carruth21206d52011-02-23 23:34:11 +00006110 llvm::APSInt Right;
6111 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006112 if (RHS.get()->isValueDependent() ||
6113 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006114 return;
6115
6116 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006117 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006118 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006119 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006120 return;
6121 }
6122 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006123 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006124 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006125 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006126 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006127 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006128 return;
6129 }
6130 if (Opc != BO_Shl)
6131 return;
6132
6133 // When left shifting an ICE which is signed, we can check for overflow which
6134 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6135 // integers have defined behavior modulo one more than the maximum value
6136 // representable in the result type, so never warn for those.
6137 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006138 if (LHS.get()->isValueDependent() ||
6139 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6140 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00006141 return;
6142 llvm::APInt ResultBits =
6143 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6144 if (LeftBits.uge(ResultBits))
6145 return;
6146 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6147 Result = Result.shl(Right);
6148
Ted Kremenekfa821382011-06-15 00:54:52 +00006149 // Print the bit representation of the signed integer as an unsigned
6150 // hexadecimal number.
6151 llvm::SmallString<40> HexResult;
6152 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6153
Chandler Carruth21206d52011-02-23 23:34:11 +00006154 // If we are only missing a sign bit, this is less likely to result in actual
6155 // bugs -- if the result is cast back to an unsigned type, it will have the
6156 // expected value. Thus we place this behind a different warning that can be
6157 // turned off separately if needed.
6158 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006159 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006160 << HexResult.str() << LHSType
6161 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006162 return;
6163 }
6164
6165 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006166 << HexResult.str() << Result.getMinSignedBits() << LHSType
6167 << Left.getBitWidth() << LHS.get()->getSourceRange()
6168 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006169}
6170
Chris Lattnereca7be62008-04-07 05:30:13 +00006171// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006172QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006173 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006174 bool IsCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00006175 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006176 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6177 !RHS.get()->getType()->hasIntegerRepresentation())
6178 return InvalidOperands(Loc, LHS, RHS);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006179
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006180 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6181 // hasIntegerRepresentation() above instead of this.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006182 if (isScopedEnumerationType(LHS.get()->getType()) ||
6183 isScopedEnumerationType(RHS.get()->getType())) {
6184 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006185 }
6186
Nate Begeman2207d792009-10-25 02:26:48 +00006187 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006188 if (LHS.get()->getType()->isVectorType() ||
6189 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006190 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006191
Chris Lattnerca5eede2007-12-12 05:47:28 +00006192 // Shifts don't perform usual arithmetic conversions, they just do integer
6193 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006194
John McCall1bc80af2010-12-16 19:28:59 +00006195 // For the LHS, do usual unary conversions, but then reset them away
6196 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006197 ExprResult OldLHS = LHS;
6198 LHS = UsualUnaryConversions(LHS.take());
6199 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006200 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006201 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00006202 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00006203
6204 // The RHS is simpler.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006205 RHS = UsualUnaryConversions(RHS.take());
6206 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006207 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006208
Ryan Flynnd0439682009-08-07 16:20:20 +00006209 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006210 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00006211
Chris Lattnerca5eede2007-12-12 05:47:28 +00006212 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006213 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006214}
6215
Chandler Carruth99919472010-07-10 12:30:03 +00006216static bool IsWithinTemplateSpecialization(Decl *D) {
6217 if (DeclContext *DC = D->getDeclContext()) {
6218 if (isa<ClassTemplateSpecializationDecl>(DC))
6219 return true;
6220 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6221 return FD->isFunctionTemplateSpecialization();
6222 }
6223 return false;
6224}
6225
Richard Trieue648ac32011-09-02 03:48:46 +00006226/// If two different enums are compared, raise a warning.
Richard Trieuba261492011-09-06 21:27:33 +00006227static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6228 ExprResult &RHS) {
6229 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6230 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00006231
6232 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6233 if (!LHSEnumType)
6234 return;
6235 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6236 if (!RHSEnumType)
6237 return;
6238
6239 // Ignore anonymous enums.
6240 if (!LHSEnumType->getDecl()->getIdentifier())
6241 return;
6242 if (!RHSEnumType->getDecl()->getIdentifier())
6243 return;
6244
6245 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6246 return;
6247
6248 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6249 << LHSStrippedType << RHSStrippedType
Richard Trieuba261492011-09-06 21:27:33 +00006250 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00006251}
6252
Richard Trieu7be1be02011-09-02 02:55:45 +00006253/// \brief Diagnose bad pointer comparisons.
6254static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006255 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006256 bool IsError) {
6257 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00006258 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00006259 << LHS.get()->getType() << RHS.get()->getType()
6260 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006261}
6262
6263/// \brief Returns false if the pointers are converted to a composite type,
6264/// true otherwise.
6265static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006266 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006267 // C++ [expr.rel]p2:
6268 // [...] Pointer conversions (4.10) and qualification
6269 // conversions (4.4) are performed on pointer operands (or on
6270 // a pointer operand and a null pointer constant) to bring
6271 // them to their composite pointer type. [...]
6272 //
6273 // C++ [expr.eq]p1 uses the same notion for (in)equality
6274 // comparisons of pointers.
6275
6276 // C++ [expr.eq]p2:
6277 // In addition, pointers to members can be compared, or a pointer to
6278 // member and a null pointer constant. Pointer to member conversions
6279 // (4.11) and qualification conversions (4.4) are performed to bring
6280 // them to a common type. If one operand is a null pointer constant,
6281 // the common type is the type of the other operand. Otherwise, the
6282 // common type is a pointer to member type similar (4.4) to the type
6283 // of one of the operands, with a cv-qualification signature (4.4)
6284 // that is the union of the cv-qualification signatures of the operand
6285 // types.
6286
Richard Trieuba261492011-09-06 21:27:33 +00006287 QualType LHSType = LHS.get()->getType();
6288 QualType RHSType = RHS.get()->getType();
6289 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6290 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00006291
6292 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006293 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00006294 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006295 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00006296 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00006297 return true;
6298 }
6299
6300 if (NonStandardCompositeType)
6301 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00006302 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6303 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006304
Richard Trieuba261492011-09-06 21:27:33 +00006305 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6306 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00006307 return false;
6308}
6309
6310static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006311 ExprResult &LHS,
6312 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006313 bool IsError) {
6314 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6315 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00006316 << LHS.get()->getType() << RHS.get()->getType()
6317 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006318}
6319
Douglas Gregor0c6db942009-05-04 06:07:12 +00006320// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00006321QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006322 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006323 bool IsRelational) {
John McCall2de56d12010-08-25 11:45:40 +00006324 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006325
Chris Lattner02dd4b12009-12-05 05:40:13 +00006326 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006327 if (LHS.get()->getType()->isVectorType() ||
6328 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006329 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006330
Richard Trieuf1775fb2011-09-06 21:43:51 +00006331 QualType LHSType = LHS.get()->getType();
6332 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00006333
Richard Trieuf1775fb2011-09-06 21:43:51 +00006334 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6335 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006336
Richard Trieuf1775fb2011-09-06 21:43:51 +00006337 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth543cb652011-02-17 08:37:06 +00006338
Richard Trieuf1775fb2011-09-06 21:43:51 +00006339 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00006340 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006341 !LHS.get()->getLocStart().isMacroID() &&
6342 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006343 // For non-floating point types, check for self-comparisons of the form
6344 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6345 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006346 //
6347 // NOTE: Don't warn about comparison expressions resulting from macro
6348 // expansion. Also don't warn about comparisons which are only self
6349 // comparisons within a template specialization. The warnings should catch
6350 // obvious cases in the definition of the template anyways. The idea is to
6351 // warn when the typed comparison operator will always evaluate to the same
6352 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006353 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006354 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006355 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006356 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006357 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006358 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006359 << (Opc == BO_EQ
6360 || Opc == BO_LE
6361 || Opc == BO_GE));
Richard Trieuf1775fb2011-09-06 21:43:51 +00006362 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregord64fdd02010-06-08 19:50:34 +00006363 !DRL->getDecl()->getType()->isReferenceType() &&
6364 !DRR->getDecl()->getType()->isReferenceType()) {
6365 // what is it always going to eval to?
6366 char always_evals_to;
6367 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006368 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006369 always_evals_to = 0; // false
6370 break;
John McCall2de56d12010-08-25 11:45:40 +00006371 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006372 always_evals_to = 1; // true
6373 break;
6374 default:
6375 // best we can say is 'a constant'
6376 always_evals_to = 2; // e.g. array1 <= array2
6377 break;
6378 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006379 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006380 << 1 // array
6381 << always_evals_to);
6382 }
6383 }
Chandler Carruth99919472010-07-10 12:30:03 +00006384 }
Mike Stump1eb44332009-09-09 15:08:12 +00006385
Chris Lattner55660a72009-03-08 19:39:53 +00006386 if (isa<CastExpr>(LHSStripped))
6387 LHSStripped = LHSStripped->IgnoreParenCasts();
6388 if (isa<CastExpr>(RHSStripped))
6389 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006390
Chris Lattner55660a72009-03-08 19:39:53 +00006391 // Warn about comparisons against a string constant (unless the other
6392 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006393 Expr *literalString = 0;
6394 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006395 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006396 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006397 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006398 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006399 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006400 } else if ((isa<StringLiteral>(RHSStripped) ||
6401 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006402 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006403 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006404 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006405 literalStringStripped = RHSStripped;
6406 }
6407
6408 if (literalString) {
6409 std::string resultComparison;
6410 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006411 case BO_LT: resultComparison = ") < 0"; break;
6412 case BO_GT: resultComparison = ") > 0"; break;
6413 case BO_LE: resultComparison = ") <= 0"; break;
6414 case BO_GE: resultComparison = ") >= 0"; break;
6415 case BO_EQ: resultComparison = ") == 0"; break;
6416 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00006417 default: assert(false && "Invalid comparison operator");
6418 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006419
Ted Kremenek351ba912011-02-23 01:52:04 +00006420 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006421 PDiag(diag::warn_stringcompare)
6422 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006423 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006424 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006425 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006426
Douglas Gregord64fdd02010-06-08 19:50:34 +00006427 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieuf1775fb2011-09-06 21:43:51 +00006428 if (LHS.get()->getType()->isArithmeticType() &&
6429 RHS.get()->getType()->isArithmeticType()) {
6430 UsualArithmeticConversions(LHS, RHS);
6431 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006432 return QualType();
6433 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00006434 else {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006435 LHS = UsualUnaryConversions(LHS.take());
6436 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006437 return QualType();
6438
Richard Trieuf1775fb2011-09-06 21:43:51 +00006439 RHS = UsualUnaryConversions(RHS.take());
6440 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006441 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006442 }
6443
Richard Trieuf1775fb2011-09-06 21:43:51 +00006444 LHSType = LHS.get()->getType();
6445 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006446
Douglas Gregor447b69e2008-11-19 03:25:36 +00006447 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00006448 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00006449
Richard Trieuccd891a2011-09-09 01:45:06 +00006450 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006451 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006452 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006453 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006454 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006455 if (LHSType->hasFloatingRepresentation())
6456 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006457
Richard Trieuf1775fb2011-09-06 21:43:51 +00006458 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006459 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006460 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006461
Richard Trieuf1775fb2011-09-06 21:43:51 +00006462 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006463 Expr::NPC_ValueDependentIsNull);
Richard Trieuf1775fb2011-09-06 21:43:51 +00006464 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006465 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006466
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006467 // All of the following pointer-related warnings are GCC extensions, except
6468 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006469 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00006470 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00006471 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00006472 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00006473 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006474
Douglas Gregor0c6db942009-05-04 06:07:12 +00006475 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00006476 if (LCanPointeeTy == RCanPointeeTy)
6477 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00006478 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006479 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6480 // Valid unless comparison between non-null pointer and function pointer
6481 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006482 // In a SFINAE context, we treat this as a hard error to maintain
6483 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006484 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6485 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006486 diagnoseFunctionPointerToVoidComparison(
Richard Trieuf1775fb2011-09-06 21:43:51 +00006487 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006488
6489 if (isSFINAEContext())
6490 return QualType();
6491
Richard Trieuf1775fb2011-09-06 21:43:51 +00006492 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006493 return ResultTy;
6494 }
6495 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006496
Richard Trieuf1775fb2011-09-06 21:43:51 +00006497 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00006498 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00006499 else
6500 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00006501 }
Eli Friedman3075e762009-08-23 00:27:47 +00006502 // C99 6.5.9p2 and C99 6.5.8p2
6503 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6504 RCanPointeeTy.getUnqualifiedType())) {
6505 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00006506 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00006507 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006508 << LHSType << RHSType << LHS.get()->getSourceRange()
6509 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00006510 }
Richard Trieuccd891a2011-09-09 01:45:06 +00006511 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00006512 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6513 // Valid unless comparison between non-null pointer and function pointer
6514 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00006515 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006516 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00006517 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00006518 } else {
6519 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00006520 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00006521 }
John McCall34d6f932011-03-11 04:25:25 +00006522 if (LCanPointeeTy != RCanPointeeTy) {
6523 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006524 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006525 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00006526 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006527 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00006528 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00006529 }
Mike Stump1eb44332009-09-09 15:08:12 +00006530
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006531 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006532 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006533 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006534 return ResultTy;
6535
Mike Stump1eb44332009-09-09 15:08:12 +00006536 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00006537 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00006538 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006539 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00006540 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006541 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6542 RHS = ImpCastExprToType(RHS.take(), LHSType,
6543 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006544 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006545 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006546 return ResultTy;
6547 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006548 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006549 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00006550 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006551 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6552 LHS = ImpCastExprToType(LHS.take(), RHSType,
6553 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006554 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006555 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006556 return ResultTy;
6557 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006558
6559 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00006560 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006561 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6562 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00006563 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00006564 else
6565 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00006566 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006567
6568 // Handle scoped enumeration types specifically, since they don't promote
6569 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006570 if (LHS.get()->getType()->isEnumeralType() &&
6571 Context.hasSameUnqualifiedType(LHS.get()->getType(),
6572 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00006573 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006574 }
Mike Stump1eb44332009-09-09 15:08:12 +00006575
Steve Naroff1c7d0672008-09-04 15:10:53 +00006576 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00006577 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006578 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00006579 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6580 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006581
Steve Naroff1c7d0672008-09-04 15:10:53 +00006582 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00006583 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006584 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006585 << LHSType << RHSType << LHS.get()->getSourceRange()
6586 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00006587 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00006588 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006589 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006590 }
John Wiegley429bb272011-04-08 18:41:53 +00006591
Steve Naroff59f53942008-09-28 01:11:11 +00006592 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00006593 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00006594 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6595 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00006596 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006597 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006598 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00006599 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006600 ->getPointeeType()->isVoidType())))
6601 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006602 << LHSType << RHSType << LHS.get()->getSourceRange()
6603 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00006604 }
John McCall34d6f932011-03-11 04:25:25 +00006605 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00006606 LHS = ImpCastExprToType(LHS.take(), RHSType,
6607 RHSType->isPointerType() ? CK_BitCast
6608 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00006609 else
John McCall1d9b3b22011-09-09 05:25:32 +00006610 RHS = ImpCastExprToType(RHS.take(), LHSType,
6611 LHSType->isPointerType() ? CK_BitCast
6612 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006613 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00006614 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00006615
Richard Trieuf1775fb2011-09-06 21:43:51 +00006616 if (LHSType->isObjCObjectPointerType() ||
6617 RHSType->isObjCObjectPointerType()) {
6618 const PointerType *LPT = LHSType->getAs<PointerType>();
6619 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00006620 if (LPT || RPT) {
6621 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6622 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006623
Steve Naroffa8069f12008-11-17 19:49:16 +00006624 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006625 !Context.typesAreCompatible(LHSType, RHSType)) {
6626 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00006627 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00006628 }
John McCall34d6f932011-03-11 04:25:25 +00006629 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00006630 LHS = ImpCastExprToType(LHS.take(), RHSType,
6631 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00006632 else
John McCall1d9b3b22011-09-09 05:25:32 +00006633 RHS = ImpCastExprToType(RHS.take(), LHSType,
6634 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006635 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00006636 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00006637 if (LHSType->isObjCObjectPointerType() &&
6638 RHSType->isObjCObjectPointerType()) {
6639 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6640 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00006641 /*isError*/false);
John McCall34d6f932011-03-11 04:25:25 +00006642 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006643 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006644 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00006645 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006646 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00006647 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00006648 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00006649 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6650 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006651 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006652 bool isError = false;
Richard Trieuf1775fb2011-09-06 21:43:51 +00006653 if ((LHSIsNull && LHSType->isIntegerType()) ||
6654 (RHSIsNull && RHSType->isIntegerType())) {
Richard Trieuccd891a2011-09-09 01:45:06 +00006655 if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006656 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Richard Trieuccd891a2011-09-09 01:45:06 +00006657 } else if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006658 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006659 else if (getLangOptions().CPlusPlus) {
6660 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6661 isError = true;
6662 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006663 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00006664
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006665 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006666 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006667 << LHSType << RHSType << LHS.get()->getSourceRange()
6668 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006669 if (isError)
6670 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00006671 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006672
Richard Trieuf1775fb2011-09-06 21:43:51 +00006673 if (LHSType->isIntegerType())
6674 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00006675 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006676 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00006677 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00006678 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006679 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006680 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006681
Steve Naroff39218df2008-09-04 16:56:14 +00006682 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00006683 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00006684 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6685 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006686 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006687 }
Richard Trieuccd891a2011-09-09 01:45:06 +00006688 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00006689 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6690 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006691 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006692 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006693
Richard Trieuf1775fb2011-09-06 21:43:51 +00006694 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006695}
6696
Nate Begemanbe2341d2008-07-14 18:02:46 +00006697/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00006698/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006699/// like a scalar comparison, a vector comparison produces a vector of integer
6700/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006701QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006702 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006703 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00006704 // Check to make sure we're operating on vectors of the same type and width,
6705 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006706 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00006707 if (vType.isNull())
6708 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006709
Richard Trieu9f60dee2011-09-07 01:19:57 +00006710 QualType LHSType = LHS.get()->getType();
6711 QualType RHSType = RHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006712
Anton Yartsev7870b132011-03-27 15:36:07 +00006713 // If AltiVec, the comparison results in a numeric type, i.e.
6714 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00006715 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00006716 return Context.getLogicalOperationType();
6717
Nate Begemanbe2341d2008-07-14 18:02:46 +00006718 // For non-floating point types, check for self-comparisons of the form
6719 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6720 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006721 if (!LHSType->hasFloatingRepresentation()) {
6722 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
6723 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParens()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006724 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00006725 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00006726 PDiag(diag::warn_comparison_always)
6727 << 0 // self-
6728 << 2 // "a constant"
6729 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00006730 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006731
Nate Begemanbe2341d2008-07-14 18:02:46 +00006732 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00006733 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00006734 assert (RHSType->hasFloatingRepresentation());
6735 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00006736 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006737
Nate Begemanbe2341d2008-07-14 18:02:46 +00006738 // Return the type for the comparison, which is the same as vector type for
6739 // integer vectors, or an integer type of identical size and number of
6740 // elements for floating point vectors.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006741 if (LHSType->hasIntegerRepresentation())
6742 return LHSType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006743
Richard Trieu9f60dee2011-09-07 01:19:57 +00006744 const VectorType *VTy = LHSType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00006745 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00006746 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006747 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00006748 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00006749 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6750
Mike Stumpeed9cac2009-02-19 03:04:26 +00006751 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00006752 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00006753 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6754}
6755
Reid Spencer5f016e22007-07-11 17:01:13 +00006756inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00006757 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00006758 if (LHS.get()->getType()->isVectorType() ||
6759 RHS.get()->getType()->isVectorType()) {
6760 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6761 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00006762 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00006763
Richard Trieu9f60dee2011-09-07 01:19:57 +00006764 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00006765 }
Steve Naroff90045e82007-07-13 23:32:42 +00006766
Richard Trieu9f60dee2011-09-07 01:19:57 +00006767 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
6768 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00006769 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00006770 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006771 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00006772 LHS = LHSResult.take();
6773 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006774
Richard Trieu9f60dee2011-09-07 01:19:57 +00006775 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6776 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006777 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00006778 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006779}
6780
6781inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00006782 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00006783
6784 // Diagnose cases where the user write a logical and/or but probably meant a
6785 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6786 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006787 if (LHS.get()->getType()->isIntegerType() &&
6788 !LHS.get()->getType()->isBooleanType() &&
6789 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00006790 // Don't warn in macros or template instantiations.
6791 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00006792 // If the RHS can be constant folded, and if it constant folds to something
6793 // that isn't 0 or 1 (which indicate a potential logical operation that
6794 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00006795 // Parens on the RHS are ignored.
Chris Lattnerb7690b42010-07-24 01:10:11 +00006796 Expr::EvalResult Result;
Richard Trieu9f60dee2011-09-07 01:19:57 +00006797 if (RHS.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6798 if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) ||
Chandler Carruth0683a142011-05-31 05:41:42 +00006799 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6800 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00006801 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006802 << (Opc == BO_LAnd ? "&&" : "||");
6803 // Suggest replacing the logical operator with the bitwise version
6804 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6805 << (Opc == BO_LAnd ? "&" : "|")
6806 << FixItHint::CreateReplacement(SourceRange(
6807 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6808 getLangOptions())),
6809 Opc == BO_LAnd ? "&" : "|");
6810 if (Opc == BO_LAnd)
6811 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6812 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6813 << FixItHint::CreateRemoval(
6814 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00006815 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006816 0, getSourceManager(),
6817 getLangOptions()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00006818 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006819 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00006820 }
Chris Lattner90a8f272010-07-13 19:41:32 +00006821
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006822 if (!Context.getLangOptions().CPlusPlus) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00006823 LHS = UsualUnaryConversions(LHS.take());
6824 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006825 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006826
Richard Trieu9f60dee2011-09-07 01:19:57 +00006827 RHS = UsualUnaryConversions(RHS.take());
6828 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006829 return QualType();
6830
Richard Trieu9f60dee2011-09-07 01:19:57 +00006831 if (!LHS.get()->getType()->isScalarType() ||
6832 !RHS.get()->getType()->isScalarType())
6833 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006834
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006835 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00006836 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006837
John McCall75f7c0f2010-06-04 00:29:51 +00006838 // The following is safe because we only use this method for
6839 // non-overloadable operands.
6840
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006841 // C++ [expr.log.and]p1
6842 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00006843 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006844 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
6845 if (LHSRes.isInvalid())
6846 return InvalidOperands(Loc, LHS, RHS);
6847 LHS = move(LHSRes);
John Wiegley429bb272011-04-08 18:41:53 +00006848
Richard Trieu9f60dee2011-09-07 01:19:57 +00006849 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
6850 if (RHSRes.isInvalid())
6851 return InvalidOperands(Loc, LHS, RHS);
6852 RHS = move(RHSRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006853
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006854 // C++ [expr.log.and]p2
6855 // C++ [expr.log.or]p2
6856 // The result is a bool.
6857 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006858}
6859
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006860/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6861/// is a read-only property; return true if so. A readonly property expression
6862/// depends on various declarations and thus must be treated specially.
6863///
Mike Stump1eb44332009-09-09 15:08:12 +00006864static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006865 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6866 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00006867 if (PropExpr->isImplicitProperty()) return false;
6868
6869 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6870 QualType BaseType = PropExpr->isSuperReceiver() ?
6871 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00006872 PropExpr->getBase()->getType();
6873
John McCall12f78a62010-12-02 01:19:52 +00006874 if (const ObjCObjectPointerType *OPT =
6875 BaseType->getAsObjCInterfacePointerType())
6876 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6877 if (S.isPropertyReadonly(PDecl, IFace))
6878 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006879 }
6880 return false;
6881}
6882
Fariborz Jahanian14086762011-03-28 23:47:18 +00006883static bool IsConstProperty(Expr *E, Sema &S) {
6884 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6885 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6886 if (PropExpr->isImplicitProperty()) return false;
6887
6888 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6889 QualType T = PDecl->getType();
6890 if (T->isReferenceType())
Fariborz Jahanian61750f22011-03-30 16:59:30 +00006891 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanian14086762011-03-28 23:47:18 +00006892 CanQualType CT = S.Context.getCanonicalType(T);
6893 return CT.isConstQualified();
6894 }
6895 return false;
6896}
6897
Fariborz Jahanian077f4902011-03-26 19:48:30 +00006898static bool IsReadonlyMessage(Expr *E, Sema &S) {
6899 if (E->getStmtClass() != Expr::MemberExprClass)
6900 return false;
6901 const MemberExpr *ME = cast<MemberExpr>(E);
6902 NamedDecl *Member = ME->getMemberDecl();
6903 if (isa<FieldDecl>(Member)) {
6904 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6905 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6906 return false;
6907 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6908 }
6909 return false;
6910}
6911
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006912/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6913/// emit an error and return true. If so, return false.
6914static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006915 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00006916 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006917 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006918 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6919 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian14086762011-03-28 23:47:18 +00006920 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6921 IsLV = Expr::MLV_Valid;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00006922 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6923 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006924 if (IsLV == Expr::MLV_Valid)
6925 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006926
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006927 unsigned Diag = 0;
6928 bool NeedType = false;
6929 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00006930 case Expr::MLV_ConstQualified:
6931 Diag = diag::err_typecheck_assign_const;
6932
John McCall7acddac2011-06-17 06:42:21 +00006933 // In ARC, use some specialized diagnostics for occasions where we
6934 // infer 'const'. These are always pseudo-strong variables.
John McCallf85e1932011-06-15 23:02:42 +00006935 if (S.getLangOptions().ObjCAutoRefCount) {
6936 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6937 if (declRef && isa<VarDecl>(declRef->getDecl())) {
6938 VarDecl *var = cast<VarDecl>(declRef->getDecl());
6939
John McCall7acddac2011-06-17 06:42:21 +00006940 // Use the normal diagnostic if it's pseudo-__strong but the
6941 // user actually wrote 'const'.
6942 if (var->isARCPseudoStrong() &&
6943 (!var->getTypeSourceInfo() ||
6944 !var->getTypeSourceInfo()->getType().isConstQualified())) {
6945 // There are two pseudo-strong cases:
6946 // - self
John McCallf85e1932011-06-15 23:02:42 +00006947 ObjCMethodDecl *method = S.getCurMethodDecl();
6948 if (method && var == method->getSelfDecl())
6949 Diag = diag::err_typecheck_arr_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00006950
6951 // - fast enumeration variables
6952 else
John McCallf85e1932011-06-15 23:02:42 +00006953 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00006954
John McCallf85e1932011-06-15 23:02:42 +00006955 SourceRange Assign;
6956 if (Loc != OrigLoc)
6957 Assign = SourceRange(OrigLoc, OrigLoc);
6958 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6959 // We need to preserve the AST regardless, so migration tool
6960 // can do its job.
6961 return false;
6962 }
6963 }
6964 }
6965
6966 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006967 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006968 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6969 NeedType = true;
6970 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006971 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006972 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6973 NeedType = true;
6974 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00006975 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006976 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6977 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00006978 case Expr::MLV_Valid:
6979 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00006980 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00006981 case Expr::MLV_MemberFunction:
6982 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006983 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6984 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006985 case Expr::MLV_IncompleteType:
6986 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00006987 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006988 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00006989 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00006990 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006991 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6992 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00006993 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006994 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6995 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00006996 case Expr::MLV_ReadonlyProperty:
6997 Diag = diag::error_readonly_property_assignment;
6998 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00006999 case Expr::MLV_NoSetterProperty:
7000 Diag = diag::error_nosetter_property_assignment;
7001 break;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007002 case Expr::MLV_InvalidMessageExpression:
7003 Diag = diag::error_readonly_message_assignment;
7004 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007005 case Expr::MLV_SubObjCPropertySetting:
7006 Diag = diag::error_no_subobject_property_setting;
7007 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007008 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007009
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007010 SourceRange Assign;
7011 if (Loc != OrigLoc)
7012 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007013 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007014 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007015 else
Mike Stump1eb44332009-09-09 15:08:12 +00007016 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007017 return true;
7018}
7019
7020
7021
7022// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00007023QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007024 SourceLocation Loc,
7025 QualType CompoundType) {
7026 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00007027 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007028 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007029
Richard Trieu268942b2011-09-07 01:33:52 +00007030 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007031 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7032 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007033 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007034 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007035 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007036 // Simple assignment "x = y".
Richard Trieu268942b2011-09-07 01:33:52 +00007037 if (LHSExpr->getObjectKind() == OK_ObjCProperty) {
7038 ExprResult LHSResult = Owned(LHSExpr);
John Wiegley429bb272011-04-08 18:41:53 +00007039 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7040 if (LHSResult.isInvalid())
7041 return QualType();
Richard Trieu268942b2011-09-07 01:33:52 +00007042 LHSExpr = LHSResult.take();
John Wiegley429bb272011-04-08 18:41:53 +00007043 }
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007044 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007045 if (RHS.isInvalid())
7046 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007047 // Special case of NSObject attributes on c-style pointer types.
7048 if (ConvTy == IncompatiblePointer &&
7049 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007050 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007051 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007052 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007053 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007054
John McCallf89e55a2010-11-18 06:31:45 +00007055 if (ConvTy == Compatible &&
7056 getLangOptions().ObjCNonFragileABI &&
7057 LHSType->isObjCObjectType())
7058 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7059 << LHSType;
7060
Chris Lattner2c156472008-08-21 18:04:13 +00007061 // If the RHS is a unary plus or minus, check to see if they = and + are
7062 // right next to each other. If so, the user may have typo'd "x =+ 4"
7063 // instead of "x += 4".
John Wiegley429bb272011-04-08 18:41:53 +00007064 Expr *RHSCheck = RHS.get();
Chris Lattner2c156472008-08-21 18:04:13 +00007065 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7066 RHSCheck = ICE->getSubExpr();
7067 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007068 if ((UO->getOpcode() == UO_Plus ||
7069 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007070 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007071 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00007072 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7073 // And there is a space or other character before the subexpr of the
7074 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00007075 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7076 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007077 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007078 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007079 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007080 }
Chris Lattner2c156472008-08-21 18:04:13 +00007081 }
John McCallf85e1932011-06-15 23:02:42 +00007082
7083 if (ConvTy == Compatible) {
7084 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieu268942b2011-09-07 01:33:52 +00007085 checkRetainCycles(LHSExpr, RHS.get());
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007086 else if (getLangOptions().ObjCAutoRefCount)
Richard Trieu268942b2011-09-07 01:33:52 +00007087 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCallf85e1932011-06-15 23:02:42 +00007088 }
Chris Lattner2c156472008-08-21 18:04:13 +00007089 } else {
7090 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007091 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007092 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007093
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007094 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007095 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007096 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007097
Richard Trieu268942b2011-09-07 01:33:52 +00007098 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007099
Reid Spencer5f016e22007-07-11 17:01:13 +00007100 // C99 6.5.16p3: The type of an assignment expression is the type of the
7101 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007102 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007103 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7104 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007105 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007106 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00007107 return (getLangOptions().CPlusPlus
7108 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007109}
7110
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007111// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007112static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007113 SourceLocation Loc) {
John Wiegley429bb272011-04-08 18:41:53 +00007114 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00007115
John McCallfb8721c2011-04-10 19:13:55 +00007116 LHS = S.CheckPlaceholderExpr(LHS.take());
7117 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007118 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007119 return QualType();
7120
John McCallcf2e5062010-10-12 07:14:40 +00007121 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7122 // operands, but not unary promotions.
7123 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007124
John McCallf6a16482010-12-04 03:47:34 +00007125 // So we treat the LHS as a ignored value, and in C++ we allow the
7126 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007127 LHS = S.IgnoredValueConversions(LHS.take());
7128 if (LHS.isInvalid())
7129 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007130
7131 if (!S.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007132 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7133 if (RHS.isInvalid())
7134 return QualType();
7135 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007136 S.RequireCompleteType(Loc, RHS.get()->getType(),
7137 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007138 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007139
John Wiegley429bb272011-04-08 18:41:53 +00007140 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007141}
7142
Steve Naroff49b45262007-07-13 16:58:59 +00007143/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7144/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007145static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7146 ExprValueKind &VK,
7147 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007148 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007149 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007150 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007151
Chris Lattner3528d352008-11-21 07:05:48 +00007152 QualType ResType = Op->getType();
7153 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007154
John McCall09431682010-11-18 19:01:18 +00007155 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007156 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00007157 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00007158 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007159 return QualType();
7160 }
7161 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007162 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007163 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007164 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007165 } else if (ResType->isAnyPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007166 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007167 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007168 return QualType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00007169
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007170 // Diagnose bad cases where we step over interface counts.
Richard Trieudb44a6b2011-09-01 22:53:23 +00007171 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007172 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007173 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007174 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007175 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007176 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007177 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007178 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007179 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007180 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007181 IsInc, IsPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00007182 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7183 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007184 } else {
John McCall09431682010-11-18 19:01:18 +00007185 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00007186 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007187 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007188 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007189 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007190 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007191 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007192 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007193 // In C++, a prefix increment is the same type as the operand. Otherwise
7194 // (in C or with postfix), the increment is the unqualified type of the
7195 // operand.
Richard Trieuccd891a2011-09-09 01:45:06 +00007196 if (IsPrefix && S.getLangOptions().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007197 VK = VK_LValue;
7198 return ResType;
7199 } else {
7200 VK = VK_RValue;
7201 return ResType.getUnqualifiedType();
7202 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007203}
7204
John Wiegley429bb272011-04-08 18:41:53 +00007205ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCallf6a16482010-12-04 03:47:34 +00007206 assert(E->getValueKind() == VK_LValue &&
7207 E->getObjectKind() == OK_ObjCProperty);
7208 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7209
Douglas Gregor926df6c2011-06-11 01:09:30 +00007210 QualType T = E->getType();
7211 QualType ReceiverType;
7212 if (PRE->isObjectReceiver())
7213 ReceiverType = PRE->getBase()->getType();
7214 else if (PRE->isSuperReceiver())
7215 ReceiverType = PRE->getSuperReceiverType();
7216 else
7217 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7218
John McCallf6a16482010-12-04 03:47:34 +00007219 ExprValueKind VK = VK_RValue;
7220 if (PRE->isImplicitProperty()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00007221 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007222 PRE->getImplicitPropertyGetter()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00007223 T = getMessageSendResultType(ReceiverType, GetterMethod,
7224 PRE->isClassReceiver(),
7225 PRE->isSuperReceiver());
7226 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007227 }
7228 else {
7229 Diag(PRE->getLocation(), diag::err_getter_not_found)
7230 << PRE->getBase()->getType();
7231 }
John McCallf6a16482010-12-04 03:47:34 +00007232 }
Douglas Gregor926df6c2011-06-11 01:09:30 +00007233
7234 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCallf6a16482010-12-04 03:47:34 +00007235 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00007236
7237 ExprResult Result = MaybeBindToTemporary(E);
7238 if (!Result.isInvalid())
7239 E = Result.take();
John Wiegley429bb272011-04-08 18:41:53 +00007240
7241 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00007242}
7243
Richard Trieu67e29332011-08-02 04:35:43 +00007244void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7245 QualType &LHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00007246 assert(LHS.get()->getValueKind() == VK_LValue &&
7247 LHS.get()->getObjectKind() == OK_ObjCProperty);
7248 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCallf6a16482010-12-04 03:47:34 +00007249
John McCallf85e1932011-06-15 23:02:42 +00007250 bool Consumed = false;
7251
John Wiegley429bb272011-04-08 18:41:53 +00007252 if (PropRef->isImplicitProperty()) {
John McCallf6a16482010-12-04 03:47:34 +00007253 // If using property-dot syntax notation for assignment, and there is a
7254 // setter, RHS expression is being passed to the setter argument. So,
7255 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley429bb272011-04-08 18:41:53 +00007256 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCallf6a16482010-12-04 03:47:34 +00007257 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7258 LHSTy = (*P)->getType();
John McCallf85e1932011-06-15 23:02:42 +00007259 Consumed = (getLangOptions().ObjCAutoRefCount &&
7260 (*P)->hasAttr<NSConsumedAttr>());
John McCallf6a16482010-12-04 03:47:34 +00007261
7262 // Otherwise, if the getter returns an l-value, just call that.
7263 } else {
John Wiegley429bb272011-04-08 18:41:53 +00007264 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCallf6a16482010-12-04 03:47:34 +00007265 ExprValueKind VK = Expr::getValueKindForType(Result);
7266 if (VK == VK_LValue) {
John Wiegley429bb272011-04-08 18:41:53 +00007267 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7268 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCallf6a16482010-12-04 03:47:34 +00007269 return;
John McCall12f78a62010-12-02 01:19:52 +00007270 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007271 }
John McCallf85e1932011-06-15 23:02:42 +00007272 } else if (getLangOptions().ObjCAutoRefCount) {
7273 const ObjCMethodDecl *setter
7274 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7275 if (setter) {
7276 ObjCMethodDecl::param_iterator P = setter->param_begin();
7277 LHSTy = (*P)->getType();
7278 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7279 }
John McCallf6a16482010-12-04 03:47:34 +00007280 }
7281
John McCallf85e1932011-06-15 23:02:42 +00007282 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7283 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007284 InitializedEntity Entity =
John McCallf85e1932011-06-15 23:02:42 +00007285 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley429bb272011-04-08 18:41:53 +00007286 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCallf85e1932011-06-15 23:02:42 +00007287 if (!ArgE.isInvalid()) {
John Wiegley429bb272011-04-08 18:41:53 +00007288 RHS = ArgE;
John McCallf85e1932011-06-15 23:02:42 +00007289 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7290 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7291 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007292 }
7293}
7294
7295
Anders Carlsson369dee42008-02-01 07:15:58 +00007296/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007297/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007298/// where the declaration is needed for type checking. We only need to
7299/// handle cases when the expression references a function designator
7300/// or is an lvalue. Here are some examples:
7301/// - &(x) => x
7302/// - &*****f => f for f a function designator.
7303/// - &s.xx => s
7304/// - &s.zz[1].yy -> s, if zz is an array
7305/// - *(x + 1) -> x, if x is an array
7306/// - &"123"[2] -> 0
7307/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007308static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007309 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007310 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007311 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007312 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007313 // If this is an arrow operator, the address is an offset from
7314 // the base's value, so the object the base refers to is
7315 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007316 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007317 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007318 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007319 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007320 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007321 // FIXME: This code shouldn't be necessary! We should catch the implicit
7322 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007323 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7324 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7325 if (ICE->getSubExpr()->getType()->isArrayType())
7326 return getPrimaryDecl(ICE->getSubExpr());
7327 }
7328 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007329 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007330 case Stmt::UnaryOperatorClass: {
7331 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007332
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007333 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007334 case UO_Real:
7335 case UO_Imag:
7336 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007337 return getPrimaryDecl(UO->getSubExpr());
7338 default:
7339 return 0;
7340 }
7341 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007342 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007343 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007344 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007345 // If the result of an implicit cast is an l-value, we care about
7346 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007347 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007348 default:
7349 return 0;
7350 }
7351}
7352
Richard Trieu5520f232011-09-07 21:46:33 +00007353namespace {
7354 enum {
7355 AO_Bit_Field = 0,
7356 AO_Vector_Element = 1,
7357 AO_Property_Expansion = 2,
7358 AO_Register_Variable = 3,
7359 AO_No_Error = 4
7360 };
7361}
Richard Trieu09a26ad2011-09-02 00:47:55 +00007362/// \brief Diagnose invalid operand for address of operations.
7363///
7364/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007365static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7366 Expr *E, unsigned Type) {
7367 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7368}
7369
Reid Spencer5f016e22007-07-11 17:01:13 +00007370/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007371/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007372/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007373/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007374/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007375/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007376/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00007377static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7378 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00007379 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007380 return S.Context.DependentTy;
7381 if (OrigOp->getType() == S.Context.OverloadTy)
7382 return S.Context.OverloadTy;
John McCall755d8492011-04-12 00:42:48 +00007383 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7384 return S.Context.UnknownAnyTy;
John McCall864c0412011-04-26 20:42:42 +00007385 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7386 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7387 << OrigOp->getSourceRange();
7388 return QualType();
7389 }
John McCall9c72c602010-08-27 09:08:28 +00007390
John McCall755d8492011-04-12 00:42:48 +00007391 assert(!OrigOp->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00007392
John McCall9c72c602010-08-27 09:08:28 +00007393 // Make sure to ignore parentheses in subsequent checks
7394 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007395
John McCall09431682010-11-18 19:01:18 +00007396 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007397 // Implement C99-only parts of addressof rules.
7398 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007399 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007400 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7401 // (assuming the deref expression is valid).
7402 return uOp->getSubExpr()->getType();
7403 }
7404 // Technically, there should be a check for array subscript
7405 // expressions here, but the result of one is always an lvalue anyway.
7406 }
John McCall5808ce42011-02-03 08:15:49 +00007407 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007408 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00007409 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007410
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007411 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007412 bool sfinae = S.isSFINAEContext();
7413 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7414 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007415 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007416 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007417 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007418 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007419 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007420 } else if (lval == Expr::LV_MemberFunction) {
7421 // If it's an instance method, make a member pointer.
7422 // The expression must have exactly the form &A::foo.
7423
7424 // If the underlying expression isn't a decl ref, give up.
7425 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007426 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007427 << OrigOp->getSourceRange();
7428 return QualType();
7429 }
7430 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7431 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7432
7433 // The id-expression was parenthesized.
7434 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00007435 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007436 << OrigOp->getSourceRange();
7437
7438 // The method was named without a qualifier.
7439 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007440 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007441 << op->getSourceRange();
7442 }
7443
John McCall09431682010-11-18 19:01:18 +00007444 return S.Context.getMemberPointerType(op->getType(),
7445 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007446 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007447 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007448 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007449 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00007450 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00007451 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00007452 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007453 return QualType();
7454 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007455 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007456 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00007457 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00007458 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007459 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00007460 AddressOfError = AO_Vector_Element;
John McCall7eb0a9e2010-11-24 05:12:34 +00007461 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007462 // cannot take address of a property expression.
Richard Trieu5520f232011-09-07 21:46:33 +00007463 AddressOfError = AO_Property_Expansion;
Steve Naroffbcb2b612008-02-29 23:30:25 +00007464 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007465 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007466 // with the register storage-class specifier.
7467 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00007468 // in C++ it is not error to take address of a register
7469 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00007470 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00007471 !S.getLangOptions().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00007472 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00007473 }
John McCallba135432009-11-21 08:51:07 +00007474 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00007475 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00007476 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00007477 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00007478 // Could be a pointer to member, though, if there is an explicit
7479 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00007480 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00007481 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007482 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00007483 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00007484 S.Diag(OpLoc,
7485 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00007486 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007487 return QualType();
7488 }
Mike Stump1eb44332009-09-09 15:08:12 +00007489
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00007490 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7491 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00007492 return S.Context.getMemberPointerType(op->getType(),
7493 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007494 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00007495 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00007496 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00007497 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00007498 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00007499
Richard Trieu5520f232011-09-07 21:46:33 +00007500 if (AddressOfError != AO_No_Error) {
7501 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7502 return QualType();
7503 }
7504
Eli Friedman441cf102009-05-16 23:27:50 +00007505 if (lval == Expr::LV_IncompleteVoidType) {
7506 // Taking the address of a void variable is technically illegal, but we
7507 // allow it in cases which are otherwise valid.
7508 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00007509 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00007510 }
7511
Reid Spencer5f016e22007-07-11 17:01:13 +00007512 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00007513 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00007514 return S.Context.getObjCObjectPointerType(op->getType());
7515 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007516}
7517
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007518/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00007519static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7520 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00007521 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007522 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007523
John Wiegley429bb272011-04-08 18:41:53 +00007524 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7525 if (ConvResult.isInvalid())
7526 return QualType();
7527 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007528 QualType OpTy = Op->getType();
7529 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00007530
7531 if (isa<CXXReinterpretCastExpr>(Op)) {
7532 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7533 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7534 Op->getSourceRange());
7535 }
7536
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007537 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7538 // is an incomplete type or void. It would be possible to warn about
7539 // dereferencing a void pointer, but it's completely well-defined, and such a
7540 // warning is unlikely to catch any mistakes.
7541 if (const PointerType *PT = OpTy->getAs<PointerType>())
7542 Result = PT->getPointeeType();
7543 else if (const ObjCObjectPointerType *OPT =
7544 OpTy->getAs<ObjCObjectPointerType>())
7545 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00007546 else {
John McCallfb8721c2011-04-10 19:13:55 +00007547 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007548 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007549 if (PR.take() != Op)
7550 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007551 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007552
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007553 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00007554 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007555 << OpTy << Op->getSourceRange();
7556 return QualType();
7557 }
John McCall09431682010-11-18 19:01:18 +00007558
7559 // Dereferences are usually l-values...
7560 VK = VK_LValue;
7561
7562 // ...except that certain expressions are never l-values in C.
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00007563 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00007564 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007565
7566 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00007567}
7568
John McCall2de56d12010-08-25 11:45:40 +00007569static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007570 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007571 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007572 switch (Kind) {
7573 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00007574 case tok::periodstar: Opc = BO_PtrMemD; break;
7575 case tok::arrowstar: Opc = BO_PtrMemI; break;
7576 case tok::star: Opc = BO_Mul; break;
7577 case tok::slash: Opc = BO_Div; break;
7578 case tok::percent: Opc = BO_Rem; break;
7579 case tok::plus: Opc = BO_Add; break;
7580 case tok::minus: Opc = BO_Sub; break;
7581 case tok::lessless: Opc = BO_Shl; break;
7582 case tok::greatergreater: Opc = BO_Shr; break;
7583 case tok::lessequal: Opc = BO_LE; break;
7584 case tok::less: Opc = BO_LT; break;
7585 case tok::greaterequal: Opc = BO_GE; break;
7586 case tok::greater: Opc = BO_GT; break;
7587 case tok::exclaimequal: Opc = BO_NE; break;
7588 case tok::equalequal: Opc = BO_EQ; break;
7589 case tok::amp: Opc = BO_And; break;
7590 case tok::caret: Opc = BO_Xor; break;
7591 case tok::pipe: Opc = BO_Or; break;
7592 case tok::ampamp: Opc = BO_LAnd; break;
7593 case tok::pipepipe: Opc = BO_LOr; break;
7594 case tok::equal: Opc = BO_Assign; break;
7595 case tok::starequal: Opc = BO_MulAssign; break;
7596 case tok::slashequal: Opc = BO_DivAssign; break;
7597 case tok::percentequal: Opc = BO_RemAssign; break;
7598 case tok::plusequal: Opc = BO_AddAssign; break;
7599 case tok::minusequal: Opc = BO_SubAssign; break;
7600 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7601 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7602 case tok::ampequal: Opc = BO_AndAssign; break;
7603 case tok::caretequal: Opc = BO_XorAssign; break;
7604 case tok::pipeequal: Opc = BO_OrAssign; break;
7605 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007606 }
7607 return Opc;
7608}
7609
John McCall2de56d12010-08-25 11:45:40 +00007610static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007611 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007612 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007613 switch (Kind) {
7614 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00007615 case tok::plusplus: Opc = UO_PreInc; break;
7616 case tok::minusminus: Opc = UO_PreDec; break;
7617 case tok::amp: Opc = UO_AddrOf; break;
7618 case tok::star: Opc = UO_Deref; break;
7619 case tok::plus: Opc = UO_Plus; break;
7620 case tok::minus: Opc = UO_Minus; break;
7621 case tok::tilde: Opc = UO_Not; break;
7622 case tok::exclaim: Opc = UO_LNot; break;
7623 case tok::kw___real: Opc = UO_Real; break;
7624 case tok::kw___imag: Opc = UO_Imag; break;
7625 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007626 }
7627 return Opc;
7628}
7629
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007630/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7631/// This warning is only emitted for builtin assignment operations. It is also
7632/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00007633static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007634 SourceLocation OpLoc) {
7635 if (!S.ActiveTemplateInstantiations.empty())
7636 return;
7637 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7638 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007639 LHSExpr = LHSExpr->IgnoreParenImpCasts();
7640 RHSExpr = RHSExpr->IgnoreParenImpCasts();
7641 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7642 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7643 if (!LHSDeclRef || !RHSDeclRef ||
7644 LHSDeclRef->getLocation().isMacroID() ||
7645 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007646 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007647 const ValueDecl *LHSDecl =
7648 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7649 const ValueDecl *RHSDecl =
7650 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7651 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007652 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007653 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007654 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007655 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007656 if (RefTy->getPointeeType().isVolatileQualified())
7657 return;
7658
7659 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00007660 << LHSDeclRef->getType()
7661 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007662}
7663
Richard Trieue648ac32011-09-02 03:48:46 +00007664// checkArithmeticNull - Detect when a NULL constant is used improperly in an
7665// expression. These are mainly cases where the null pointer is used as an
7666// integer instead of a pointer.
Richard Trieu268942b2011-09-07 01:33:52 +00007667static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00007668 SourceLocation Loc, bool IsCompare) {
Richard Trieue648ac32011-09-02 03:48:46 +00007669 // The canonical way to check for a GNU null is with isNullPointerConstant,
7670 // but we use a bit of a hack here for speed; this is a relatively
7671 // hot path, and isNullPointerConstant is slow.
Richard Trieu268942b2011-09-07 01:33:52 +00007672 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
7673 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
Richard Trieue648ac32011-09-02 03:48:46 +00007674
7675 // Detect when a NULL constant is used improperly in an expression. These
7676 // are mainly cases where the null pointer is used as an integer instead
7677 // of a pointer.
Richard Trieu268942b2011-09-07 01:33:52 +00007678 if (!LHSNull && !RHSNull)
Richard Trieue648ac32011-09-02 03:48:46 +00007679 return;
7680
Richard Trieu268942b2011-09-07 01:33:52 +00007681 QualType LHSType = LHS.get()->getType();
7682 QualType RHSType = RHS.get()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00007683
7684 // Avoid analyzing cases where the result will either be invalid (and
7685 // diagnosed as such) or entirely valid and not something to warn about.
Richard Trieu268942b2011-09-07 01:33:52 +00007686 if (LHSType->isBlockPointerType() || LHSType->isMemberPointerType() ||
7687 LHSType->isFunctionType() || RHSType->isBlockPointerType() ||
7688 RHSType->isMemberPointerType() || RHSType->isFunctionType())
Richard Trieue648ac32011-09-02 03:48:46 +00007689 return;
7690
7691 // Comparison operations would not make sense with a null pointer no matter
7692 // what the other expression is.
Richard Trieuccd891a2011-09-09 01:45:06 +00007693 if (!IsCompare) {
Richard Trieue648ac32011-09-02 03:48:46 +00007694 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
Richard Trieu268942b2011-09-07 01:33:52 +00007695 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
7696 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
Richard Trieue648ac32011-09-02 03:48:46 +00007697 return;
7698 }
7699
7700 // The rest of the operations only make sense with a null pointer
7701 // if the other expression is a pointer.
Richard Trieu268942b2011-09-07 01:33:52 +00007702 if (LHSNull == RHSNull || LHSType->isAnyPointerType() ||
7703 LHSType->canDecayToPointerType() || RHSType->isAnyPointerType() ||
7704 RHSType->canDecayToPointerType())
Richard Trieue648ac32011-09-02 03:48:46 +00007705 return;
7706
7707 S.Diag(Loc, diag::warn_null_in_comparison_operation)
Richard Trieu268942b2011-09-07 01:33:52 +00007708 << LHSNull /* LHS is NULL */
7709 << (LHSNull ? RHS.get()->getType() : LHS.get()->getType())
7710 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00007711}
Douglas Gregoreaebc752008-11-06 23:29:22 +00007712/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7713/// operator @p Opc at location @c TokLoc. This routine only supports
7714/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00007715ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007716 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00007717 Expr *LHSExpr, Expr *RHSExpr) {
7718 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007719 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00007720 // The following two variables are used for compound assignment operators
7721 QualType CompLHSTy; // Type of LHS after promotions for computation
7722 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00007723 ExprValueKind VK = VK_RValue;
7724 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00007725
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007726 // Check if a 'foo<int>' involved in a binary op, identifies a single
7727 // function unambiguously (i.e. an lvalue ala 13.4)
7728 // But since an assignment can trigger target based overload, exclude it in
7729 // our blind search. i.e:
7730 // template<class T> void f(); template<class T, class U> void f(U);
7731 // f<int> == 0; // resolve f<int> blindly
7732 // void (*p)(int); p = f<int>; // resolve f<int> using target
7733 if (Opc != BO_Assign) {
Richard Trieu78ea78b2011-09-07 01:49:20 +00007734 ExprResult resolvedLHS = CheckPlaceholderExpr(LHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007735 if (!resolvedLHS.isUsable()) return ExprError();
Richard Trieu78ea78b2011-09-07 01:49:20 +00007736 LHS = move(resolvedLHS);
John McCall1de4d4e2011-04-07 08:22:57 +00007737
Richard Trieu78ea78b2011-09-07 01:49:20 +00007738 ExprResult resolvedRHS = CheckPlaceholderExpr(RHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007739 if (!resolvedRHS.isUsable()) return ExprError();
Richard Trieu78ea78b2011-09-07 01:49:20 +00007740 RHS = move(resolvedRHS);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007741 }
7742
Richard Trieue648ac32011-09-02 03:48:46 +00007743 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
7744 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
7745 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
7746 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
7747 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
7748 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign)
Richard Trieu78ea78b2011-09-07 01:49:20 +00007749 checkArithmeticNull(*this, LHS, RHS, OpLoc, /*isCompare=*/false);
Richard Trieue648ac32011-09-02 03:48:46 +00007750 else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
7751 Opc == BO_EQ || Opc == BO_NE)
Richard Trieu78ea78b2011-09-07 01:49:20 +00007752 checkArithmeticNull(*this, LHS, RHS, OpLoc, /*isCompare=*/true);
Richard Trieu3e95ba92011-06-16 21:36:56 +00007753
Douglas Gregoreaebc752008-11-06 23:29:22 +00007754 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007755 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007756 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00007757 if (getLangOptions().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00007758 LHS.get()->getObjectKind() != OK_ObjCProperty) {
7759 VK = LHS.get()->getValueKind();
7760 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007761 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007762 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00007763 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007764 break;
John McCall2de56d12010-08-25 11:45:40 +00007765 case BO_PtrMemD:
7766 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007767 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007768 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00007769 break;
John McCall2de56d12010-08-25 11:45:40 +00007770 case BO_Mul:
7771 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007772 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00007773 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007774 break;
John McCall2de56d12010-08-25 11:45:40 +00007775 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007776 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007777 break;
John McCall2de56d12010-08-25 11:45:40 +00007778 case BO_Add:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007779 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007780 break;
John McCall2de56d12010-08-25 11:45:40 +00007781 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007782 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007783 break;
John McCall2de56d12010-08-25 11:45:40 +00007784 case BO_Shl:
7785 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007786 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007787 break;
John McCall2de56d12010-08-25 11:45:40 +00007788 case BO_LE:
7789 case BO_LT:
7790 case BO_GE:
7791 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007792 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007793 break;
John McCall2de56d12010-08-25 11:45:40 +00007794 case BO_EQ:
7795 case BO_NE:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007796 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007797 break;
John McCall2de56d12010-08-25 11:45:40 +00007798 case BO_And:
7799 case BO_Xor:
7800 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007801 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007802 break;
John McCall2de56d12010-08-25 11:45:40 +00007803 case BO_LAnd:
7804 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007805 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007806 break;
John McCall2de56d12010-08-25 11:45:40 +00007807 case BO_MulAssign:
7808 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007809 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00007810 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007811 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007812 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7813 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007814 break;
John McCall2de56d12010-08-25 11:45:40 +00007815 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007816 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007817 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007818 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7819 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007820 break;
John McCall2de56d12010-08-25 11:45:40 +00007821 case BO_AddAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007822 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7823 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7824 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007825 break;
John McCall2de56d12010-08-25 11:45:40 +00007826 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007827 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7828 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7829 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007830 break;
John McCall2de56d12010-08-25 11:45:40 +00007831 case BO_ShlAssign:
7832 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007833 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007834 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007835 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7836 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007837 break;
John McCall2de56d12010-08-25 11:45:40 +00007838 case BO_AndAssign:
7839 case BO_XorAssign:
7840 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007841 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007842 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007843 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7844 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007845 break;
John McCall2de56d12010-08-25 11:45:40 +00007846 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007847 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
7848 if (getLangOptions().CPlusPlus && !RHS.isInvalid()) {
7849 VK = RHS.get()->getValueKind();
7850 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007851 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00007852 break;
7853 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00007854 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00007855 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007856
7857 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00007858 CheckArrayAccess(LHS.get());
7859 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007860
Eli Friedmanab3a8522009-03-28 01:22:36 +00007861 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00007862 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007863 ResultTy, VK, OK, OpLoc));
Richard Trieu78ea78b2011-09-07 01:49:20 +00007864 if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00007865 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00007866 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007867 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007868 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00007869 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007870 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00007871 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00007872}
7873
Sebastian Redlaee3c932009-10-27 12:10:02 +00007874/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7875/// operators are mixed in a way that suggests that the programmer forgot that
7876/// comparison operators have higher precedence. The most typical example of
7877/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00007878static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00007879 SourceLocation OpLoc, Expr *LHSExpr,
7880 Expr *RHSExpr) {
Sebastian Redlaee3c932009-10-27 12:10:02 +00007881 typedef BinaryOperator BinOp;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007882 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
7883 RHSopc = static_cast<BinOp::Opcode>(-1);
7884 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
7885 LHSopc = BO->getOpcode();
7886 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
7887 RHSopc = BO->getOpcode();
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007888
7889 // Subs are not binary operators.
Richard Trieu78ea78b2011-09-07 01:49:20 +00007890 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007891 return;
7892
7893 // Bitwise operations are sometimes used as eager logical ops.
7894 // Don't diagnose this.
Richard Trieu78ea78b2011-09-07 01:49:20 +00007895 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
7896 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007897 return;
7898
Richard Trieu78ea78b2011-09-07 01:49:20 +00007899 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
7900 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00007901 if (!isLeftComp && !isRightComp) return;
7902
Richard Trieu78ea78b2011-09-07 01:49:20 +00007903 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
7904 OpLoc)
7905 : SourceRange(OpLoc, RHSExpr->getLocEnd());
7906 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
7907 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00007908 SourceRange ParensRange = isLeftComp ?
Richard Trieu78ea78b2011-09-07 01:49:20 +00007909 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
7910 RHSExpr->getLocEnd())
7911 : SourceRange(LHSExpr->getLocStart(),
7912 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00007913
7914 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7915 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7916 SuggestParentheses(Self, OpLoc,
7917 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Richard Trieu78ea78b2011-09-07 01:49:20 +00007918 RHSExpr->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00007919 SuggestParentheses(Self, OpLoc,
7920 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7921 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007922}
7923
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007924/// \brief It accepts a '&' expr that is inside a '|' one.
7925/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7926/// in parentheses.
7927static void
7928EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7929 BinaryOperator *Bop) {
7930 assert(Bop->getOpcode() == BO_And);
7931 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7932 << Bop->getSourceRange() << OpLoc;
7933 SuggestParentheses(Self, Bop->getOperatorLoc(),
7934 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7935 Bop->getSourceRange());
7936}
7937
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007938/// \brief It accepts a '&&' expr that is inside a '||' one.
7939/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7940/// in parentheses.
7941static void
7942EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00007943 BinaryOperator *Bop) {
7944 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007945 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7946 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00007947 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007948 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007949 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007950}
7951
7952/// \brief Returns true if the given expression can be evaluated as a constant
7953/// 'true'.
7954static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7955 bool Res;
7956 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7957}
7958
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007959/// \brief Returns true if the given expression can be evaluated as a constant
7960/// 'false'.
7961static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7962 bool Res;
7963 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7964}
7965
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007966/// \brief Look for '&&' in the left hand of a '||' expr.
7967static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00007968 Expr *LHSExpr, Expr *RHSExpr) {
7969 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007970 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007971 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00007972 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007973 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007974 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7975 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7976 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7977 } else if (Bop->getOpcode() == BO_LOr) {
7978 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7979 // If it's "a || b && 1 || c" we didn't warn earlier for
7980 // "a || b && 1", but warn now.
7981 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7982 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7983 }
7984 }
7985 }
7986}
7987
7988/// \brief Look for '&&' in the right hand of a '||' expr.
7989static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00007990 Expr *LHSExpr, Expr *RHSExpr) {
7991 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007992 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007993 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00007994 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007995 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007996 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7997 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7998 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007999 }
8000 }
8001}
8002
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008003/// \brief Look for '&' in the left or right hand of a '|' expr.
8004static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8005 Expr *OrArg) {
8006 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8007 if (Bop->getOpcode() == BO_And)
8008 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8009 }
8010}
8011
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008012/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008013/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008014static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008015 SourceLocation OpLoc, Expr *LHSExpr,
8016 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008017 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008018 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008019 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008020
8021 // Diagnose "arg1 & arg2 | arg3"
8022 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008023 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8024 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008025 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008026
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008027 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8028 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008029 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008030 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8031 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008032 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008033}
8034
Reid Spencer5f016e22007-07-11 17:01:13 +00008035// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008036ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008037 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00008038 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00008039 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00008040 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8041 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008042
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008043 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00008044 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008045
Richard Trieubefece12011-09-07 02:02:10 +00008046 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008047}
8048
John McCall60d7b3a2010-08-24 06:29:42 +00008049ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008050 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008051 Expr *LHSExpr, Expr *RHSExpr) {
John McCall01b2e4e2010-12-06 05:26:58 +00008052 if (getLangOptions().CPlusPlus) {
8053 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008054
Richard Trieubefece12011-09-07 02:02:10 +00008055 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) {
John McCall01b2e4e2010-12-06 05:26:58 +00008056 UseBuiltinOperator = false;
Richard Trieubefece12011-09-07 02:02:10 +00008057 } else if (Opc == BO_Assign &&
8058 LHSExpr->getObjectKind() == OK_ObjCProperty) {
John McCall01b2e4e2010-12-06 05:26:58 +00008059 UseBuiltinOperator = true;
8060 } else {
Richard Trieubefece12011-09-07 02:02:10 +00008061 UseBuiltinOperator = !LHSExpr->getType()->isOverloadableType() &&
8062 !RHSExpr->getType()->isOverloadableType();
John McCall01b2e4e2010-12-06 05:26:58 +00008063 }
8064
8065 if (!UseBuiltinOperator) {
8066 // Find all of the overloaded operators visible from this
8067 // point. We perform both an operator-name lookup from the local
8068 // scope and an argument-dependent lookup based on the types of
8069 // the arguments.
8070 UnresolvedSet<16> Functions;
8071 OverloadedOperatorKind OverOp
8072 = BinaryOperator::getOverloadedOperator(Opc);
8073 if (S && OverOp != OO_None)
Richard Trieubefece12011-09-07 02:02:10 +00008074 LookupOverloadedOperatorName(OverOp, S, LHSExpr->getType(),
8075 RHSExpr->getType(), Functions);
John McCall01b2e4e2010-12-06 05:26:58 +00008076
8077 // Build the (potentially-overloaded, potentially-dependent)
8078 // binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008079 return CreateOverloadedBinOp(OpLoc, Opc, Functions, LHSExpr, RHSExpr);
John McCall01b2e4e2010-12-06 05:26:58 +00008080 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008081 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008082
Douglas Gregoreaebc752008-11-06 23:29:22 +00008083 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008084 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00008085}
8086
John McCall60d7b3a2010-08-24 06:29:42 +00008087ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008088 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008089 Expr *InputExpr) {
8090 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008091 ExprValueKind VK = VK_RValue;
8092 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008093 QualType resultType;
8094 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008095 case UO_PreInc:
8096 case UO_PreDec:
8097 case UO_PostInc:
8098 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008099 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008100 Opc == UO_PreInc ||
8101 Opc == UO_PostInc,
8102 Opc == UO_PreInc ||
8103 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008104 break;
John McCall2de56d12010-08-25 11:45:40 +00008105 case UO_AddrOf:
John Wiegley429bb272011-04-08 18:41:53 +00008106 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008107 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008108 case UO_Deref: {
John McCallfb8721c2011-04-10 19:13:55 +00008109 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008110 if (!resolved.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008111 Input = move(resolved);
8112 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8113 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008114 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008115 }
John McCall2de56d12010-08-25 11:45:40 +00008116 case UO_Plus:
8117 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008118 Input = UsualUnaryConversions(Input.take());
8119 if (Input.isInvalid()) return ExprError();
8120 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008121 if (resultType->isDependentType())
8122 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008123 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8124 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008125 break;
8126 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8127 resultType->isEnumeralType())
8128 break;
8129 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008130 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008131 resultType->isPointerType())
8132 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008133 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008134 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008135 if (Input.isInvalid()) return ExprError();
8136 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008137 }
Douglas Gregor74253732008-11-19 15:42:04 +00008138
Sebastian Redl0eb23302009-01-19 00:08:26 +00008139 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008140 << resultType << Input.get()->getSourceRange());
8141
John McCall2de56d12010-08-25 11:45:40 +00008142 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008143 Input = UsualUnaryConversions(Input.take());
8144 if (Input.isInvalid()) return ExprError();
8145 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008146 if (resultType->isDependentType())
8147 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008148 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8149 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8150 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008151 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008152 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008153 else if (resultType->hasIntegerRepresentation())
8154 break;
8155 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008156 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008157 if (Input.isInvalid()) return ExprError();
8158 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008159 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008160 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008161 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008162 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008163 break;
John Wiegley429bb272011-04-08 18:41:53 +00008164
John McCall2de56d12010-08-25 11:45:40 +00008165 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008166 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008167 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8168 if (Input.isInvalid()) return ExprError();
8169 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008170 if (resultType->isDependentType())
8171 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008172 if (resultType->isScalarType()) {
8173 // C99 6.5.3.3p1: ok, fallthrough;
8174 if (Context.getLangOptions().CPlusPlus) {
8175 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8176 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008177 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8178 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008179 }
John McCall2cd11fe2010-10-12 02:09:17 +00008180 } else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008181 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008182 if (Input.isInvalid()) return ExprError();
8183 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008184 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008185 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008186 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008187 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008188
Reid Spencer5f016e22007-07-11 17:01:13 +00008189 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008190 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008191 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008192 break;
John McCall2de56d12010-08-25 11:45:40 +00008193 case UO_Real:
8194 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008195 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00008196 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley429bb272011-04-08 18:41:53 +00008197 if (Input.isInvalid()) return ExprError();
8198 if (Input.get()->getValueKind() != VK_RValue &&
8199 Input.get()->getObjectKind() == OK_Ordinary)
8200 VK = Input.get()->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00008201 break;
John McCall2de56d12010-08-25 11:45:40 +00008202 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008203 resultType = Input.get()->getType();
8204 VK = Input.get()->getValueKind();
8205 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008206 break;
8207 }
John Wiegley429bb272011-04-08 18:41:53 +00008208 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008209 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008210
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008211 // Check for array bounds violations in the operand of the UnaryOperator,
8212 // except for the '*' and '&' operators that have to be handled specially
8213 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8214 // that are explicitly defined as valid by the standard).
8215 if (Opc != UO_AddrOf && Opc != UO_Deref)
8216 CheckArrayAccess(Input.get());
8217
John Wiegley429bb272011-04-08 18:41:53 +00008218 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008219 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008220}
8221
John McCall60d7b3a2010-08-24 06:29:42 +00008222ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008223 UnaryOperatorKind Opc, Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00008224 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00008225 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008226 // Find all of the overloaded operators visible from this
8227 // point. We perform both an operator-name lookup from the local
8228 // scope and an argument-dependent lookup based on the types of
8229 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008230 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008231 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008232 if (S && OverOp != OO_None)
8233 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8234 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008235
John McCall9ae2f072010-08-23 23:25:46 +00008236 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008237 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008238
John McCall9ae2f072010-08-23 23:25:46 +00008239 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008240}
8241
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008242// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008243ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008244 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008245 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008246}
8247
Steve Naroff1b273c42007-09-16 14:56:35 +00008248/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008249ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008250 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008251 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008252 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008253 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008254 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008255}
8256
John McCallf85e1932011-06-15 23:02:42 +00008257/// Given the last statement in a statement-expression, check whether
8258/// the result is a producing expression (like a call to an
8259/// ns_returns_retained function) and, if so, rebuild it to hoist the
8260/// release out of the full-expression. Otherwise, return null.
8261/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00008262static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00008263 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00008264 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00008265 if (!cleanups) return 0;
8266
8267 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
8268 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
8269 return 0;
8270
8271 // Splice out the cast. This shouldn't modify any interesting
8272 // features of the statement.
8273 Expr *producer = cast->getSubExpr();
8274 assert(producer->getType() == cast->getType());
8275 assert(producer->getValueKind() == cast->getValueKind());
8276 cleanups->setSubExpr(producer);
8277 return cleanups;
8278}
8279
John McCall60d7b3a2010-08-24 06:29:42 +00008280ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008281Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008282 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008283 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8284 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8285
Douglas Gregordd8f5692010-03-10 04:54:39 +00008286 bool isFileScope
8287 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008288 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008289 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008290
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008291 // FIXME: there are a variety of strange constraints to enforce here, for
8292 // example, it is not possible to goto into a stmt expression apparently.
8293 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008294
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008295 // If there are sub stmts in the compound stmt, take the type of the last one
8296 // as the type of the stmtexpr.
8297 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008298 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008299 if (!Compound->body_empty()) {
8300 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008301 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008302 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008303 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8304 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008305 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008306 }
John McCallf85e1932011-06-15 23:02:42 +00008307
John Wiegley429bb272011-04-08 18:41:53 +00008308 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008309 // Do function/array conversion on the last expression, but not
8310 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00008311 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8312 if (LastExpr.isInvalid())
8313 return ExprError();
8314 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00008315
John Wiegley429bb272011-04-08 18:41:53 +00008316 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00008317 // In ARC, if the final expression ends in a consume, splice
8318 // the consume out and bind it later. In the alternate case
8319 // (when dealing with a retainable type), the result
8320 // initialization will create a produce. In both cases the
8321 // result will be +1, and we'll need to balance that out with
8322 // a bind.
8323 if (Expr *rebuiltLastStmt
8324 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8325 LastExpr = rebuiltLastStmt;
8326 } else {
8327 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008328 InitializedEntity::InitializeResult(LPLoc,
8329 Ty,
8330 false),
8331 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00008332 LastExpr);
8333 }
8334
John Wiegley429bb272011-04-08 18:41:53 +00008335 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008336 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008337 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008338 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00008339 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008340 else
John Wiegley429bb272011-04-08 18:41:53 +00008341 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008342 StmtExprMayBindToTemp = true;
8343 }
8344 }
8345 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008346 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008347
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008348 // FIXME: Check that expression type is complete/non-abstract; statement
8349 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008350 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8351 if (StmtExprMayBindToTemp)
8352 return MaybeBindToTemporary(ResStmtExpr);
8353 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008354}
Steve Naroffd34e9152007-08-01 22:05:33 +00008355
John McCall60d7b3a2010-08-24 06:29:42 +00008356ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008357 TypeSourceInfo *TInfo,
8358 OffsetOfComponent *CompPtr,
8359 unsigned NumComponents,
8360 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008361 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008362 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008363 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008364
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008365 // We must have at least one component that refers to the type, and the first
8366 // one is known to be a field designator. Verify that the ArgTy represents
8367 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008368 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008369 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8370 << ArgTy << TypeRange);
8371
8372 // Type must be complete per C99 7.17p3 because a declaring a variable
8373 // with an incomplete type would be ill-formed.
8374 if (!Dependent
8375 && RequireCompleteType(BuiltinLoc, ArgTy,
8376 PDiag(diag::err_offsetof_incomplete_type)
8377 << TypeRange))
8378 return ExprError();
8379
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008380 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8381 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00008382 // FIXME: This diagnostic isn't actually visible because the location is in
8383 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008384 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008385 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8386 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008387
8388 bool DidWarnAboutNonPOD = false;
8389 QualType CurrentType = ArgTy;
8390 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008391 SmallVector<OffsetOfNode, 4> Comps;
8392 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008393 for (unsigned i = 0; i != NumComponents; ++i) {
8394 const OffsetOfComponent &OC = CompPtr[i];
8395 if (OC.isBrackets) {
8396 // Offset of an array sub-field. TODO: Should we allow vector elements?
8397 if (!CurrentType->isDependentType()) {
8398 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8399 if(!AT)
8400 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8401 << CurrentType);
8402 CurrentType = AT->getElementType();
8403 } else
8404 CurrentType = Context.DependentTy;
8405
8406 // The expression must be an integral expression.
8407 // FIXME: An integral constant expression?
8408 Expr *Idx = static_cast<Expr*>(OC.U.E);
8409 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8410 !Idx->getType()->isIntegerType())
8411 return ExprError(Diag(Idx->getLocStart(),
8412 diag::err_typecheck_subscript_not_integer)
8413 << Idx->getSourceRange());
8414
8415 // Record this array index.
8416 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8417 Exprs.push_back(Idx);
8418 continue;
8419 }
8420
8421 // Offset of a field.
8422 if (CurrentType->isDependentType()) {
8423 // We have the offset of a field, but we can't look into the dependent
8424 // type. Just record the identifier of the field.
8425 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8426 CurrentType = Context.DependentTy;
8427 continue;
8428 }
8429
8430 // We need to have a complete type to look into.
8431 if (RequireCompleteType(OC.LocStart, CurrentType,
8432 diag::err_offsetof_incomplete_type))
8433 return ExprError();
8434
8435 // Look for the designated field.
8436 const RecordType *RC = CurrentType->getAs<RecordType>();
8437 if (!RC)
8438 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8439 << CurrentType);
8440 RecordDecl *RD = RC->getDecl();
8441
8442 // C++ [lib.support.types]p5:
8443 // The macro offsetof accepts a restricted set of type arguments in this
8444 // International Standard. type shall be a POD structure or a POD union
8445 // (clause 9).
8446 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8447 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00008448 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008449 PDiag(diag::warn_offsetof_non_pod_type)
8450 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8451 << CurrentType))
8452 DidWarnAboutNonPOD = true;
8453 }
8454
8455 // Look for the field.
8456 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8457 LookupQualifiedName(R, RD);
8458 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00008459 IndirectFieldDecl *IndirectMemberDecl = 0;
8460 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00008461 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00008462 MemberDecl = IndirectMemberDecl->getAnonField();
8463 }
8464
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008465 if (!MemberDecl)
8466 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8467 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8468 OC.LocEnd));
8469
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00008470 // C99 7.17p3:
8471 // (If the specified member is a bit-field, the behavior is undefined.)
8472 //
8473 // We diagnose this as an error.
8474 if (MemberDecl->getBitWidth()) {
8475 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8476 << MemberDecl->getDeclName()
8477 << SourceRange(BuiltinLoc, RParenLoc);
8478 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8479 return ExprError();
8480 }
Eli Friedman19410a72010-08-05 10:11:36 +00008481
8482 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00008483 if (IndirectMemberDecl)
8484 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00008485
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008486 // If the member was found in a base class, introduce OffsetOfNodes for
8487 // the base class indirections.
8488 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8489 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00008490 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008491 CXXBasePath &Path = Paths.front();
8492 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8493 B != BEnd; ++B)
8494 Comps.push_back(OffsetOfNode(B->Base));
8495 }
Eli Friedman19410a72010-08-05 10:11:36 +00008496
Francois Pichet87c2e122010-11-21 06:08:52 +00008497 if (IndirectMemberDecl) {
8498 for (IndirectFieldDecl::chain_iterator FI =
8499 IndirectMemberDecl->chain_begin(),
8500 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8501 assert(isa<FieldDecl>(*FI));
8502 Comps.push_back(OffsetOfNode(OC.LocStart,
8503 cast<FieldDecl>(*FI), OC.LocEnd));
8504 }
8505 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008506 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00008507
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008508 CurrentType = MemberDecl->getType().getNonReferenceType();
8509 }
8510
8511 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8512 TInfo, Comps.data(), Comps.size(),
8513 Exprs.data(), Exprs.size(), RParenLoc));
8514}
Mike Stumpeed9cac2009-02-19 03:04:26 +00008515
John McCall60d7b3a2010-08-24 06:29:42 +00008516ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00008517 SourceLocation BuiltinLoc,
8518 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008519 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00008520 OffsetOfComponent *CompPtr,
8521 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00008522 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00008523
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008524 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00008525 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008526 if (ArgTy.isNull())
8527 return ExprError();
8528
Eli Friedman5a15dc12010-08-05 10:15:45 +00008529 if (!ArgTInfo)
8530 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8531
8532 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00008533 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008534}
8535
8536
John McCall60d7b3a2010-08-24 06:29:42 +00008537ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008538 Expr *CondExpr,
8539 Expr *LHSExpr, Expr *RHSExpr,
8540 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00008541 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8542
John McCallf89e55a2010-11-18 06:31:45 +00008543 ExprValueKind VK = VK_RValue;
8544 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00008545 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00008546 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00008547 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00008548 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00008549 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00008550 } else {
8551 // The conditional expression is required to be a constant expression.
8552 llvm::APSInt condEval(32);
8553 SourceLocation ExpLoc;
8554 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00008555 return ExprError(Diag(ExpLoc,
8556 diag::err_typecheck_choose_expr_requires_constant)
8557 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00008558
Sebastian Redl28507842009-02-26 14:39:58 +00008559 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00008560 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8561
8562 resType = ActiveExpr->getType();
8563 ValueDependent = ActiveExpr->isValueDependent();
8564 VK = ActiveExpr->getValueKind();
8565 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00008566 }
8567
Sebastian Redlf53597f2009-03-15 17:47:39 +00008568 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008569 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00008570 resType->isDependentType(),
8571 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00008572}
8573
Steve Naroff4eb206b2008-09-03 18:15:37 +00008574//===----------------------------------------------------------------------===//
8575// Clang Extensions.
8576//===----------------------------------------------------------------------===//
8577
8578/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00008579void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008580 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00008581 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008582 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00008583 if (CurScope)
8584 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008585 else
8586 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00008587}
8588
Mike Stump98eb8a72009-02-04 22:31:32 +00008589void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00008590 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00008591 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008592 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008593
John McCallbf1a0282010-06-04 23:28:52 +00008594 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00008595 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00008596
John McCall711c52b2011-01-05 12:14:39 +00008597 // GetTypeForDeclarator always produces a function type for a block
8598 // literal signature. Furthermore, it is always a FunctionProtoType
8599 // unless the function was written with a typedef.
8600 assert(T->isFunctionType() &&
8601 "GetTypeForDeclarator made a non-function block signature");
8602
8603 // Look for an explicit signature in that function type.
8604 FunctionProtoTypeLoc ExplicitSignature;
8605
8606 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8607 if (isa<FunctionProtoTypeLoc>(tmp)) {
8608 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8609
8610 // Check whether that explicit signature was synthesized by
8611 // GetTypeForDeclarator. If so, don't save that as part of the
8612 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00008613 if (ExplicitSignature.getLocalRangeBegin() ==
8614 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00008615 // This would be much cheaper if we stored TypeLocs instead of
8616 // TypeSourceInfos.
8617 TypeLoc Result = ExplicitSignature.getResultLoc();
8618 unsigned Size = Result.getFullDataSize();
8619 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8620 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8621
8622 ExplicitSignature = FunctionProtoTypeLoc();
8623 }
John McCall82dc0092010-06-04 11:21:44 +00008624 }
Mike Stump1eb44332009-09-09 15:08:12 +00008625
John McCall711c52b2011-01-05 12:14:39 +00008626 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8627 CurBlock->FunctionType = T;
8628
8629 const FunctionType *Fn = T->getAs<FunctionType>();
8630 QualType RetTy = Fn->getResultType();
8631 bool isVariadic =
8632 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8633
John McCallc71a4912010-06-04 19:02:56 +00008634 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00008635
John McCall82dc0092010-06-04 11:21:44 +00008636 // Don't allow returning a objc interface by value.
8637 if (RetTy->isObjCObjectType()) {
8638 Diag(ParamInfo.getSourceRange().getBegin(),
8639 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8640 return;
8641 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008642
John McCall82dc0092010-06-04 11:21:44 +00008643 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00008644 // return type. TODO: what should we do with declarators like:
8645 // ^ * { ... }
8646 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00008647 if (RetTy != Context.DependentTy)
8648 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008649
John McCall82dc0092010-06-04 11:21:44 +00008650 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008651 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00008652 if (ExplicitSignature) {
8653 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8654 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008655 if (Param->getIdentifier() == 0 &&
8656 !Param->isImplicit() &&
8657 !Param->isInvalidDecl() &&
8658 !getLangOptions().CPlusPlus)
8659 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00008660 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008661 }
John McCall82dc0092010-06-04 11:21:44 +00008662
8663 // Fake up parameter variables if we have a typedef, like
8664 // ^ fntype { ... }
8665 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8666 for (FunctionProtoType::arg_type_iterator
8667 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8668 ParmVarDecl *Param =
8669 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8670 ParamInfo.getSourceRange().getBegin(),
8671 *I);
John McCallc71a4912010-06-04 19:02:56 +00008672 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00008673 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008674 }
John McCall82dc0092010-06-04 11:21:44 +00008675
John McCallc71a4912010-06-04 19:02:56 +00008676 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00008677 if (!Params.empty()) {
John McCallc71a4912010-06-04 19:02:56 +00008678 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregor82aa7132010-11-01 18:37:59 +00008679 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8680 CurBlock->TheDecl->param_end(),
8681 /*CheckParameterNames=*/false);
8682 }
8683
John McCall82dc0092010-06-04 11:21:44 +00008684 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008685 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00008686
John McCallc71a4912010-06-04 19:02:56 +00008687 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00008688 Diag(ParamInfo.getAttributes()->getLoc(),
8689 diag::warn_attribute_sentinel_not_variadic) << 1;
8690 // FIXME: remove the attribute.
8691 }
8692
8693 // Put the parameter variables in scope. We can bail out immediately
8694 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00008695 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00008696 return;
8697
Steve Naroff090276f2008-10-10 01:28:17 +00008698 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00008699 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8700 (*AI)->setOwningFunction(CurBlock->TheDecl);
8701
Steve Naroff090276f2008-10-10 01:28:17 +00008702 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00008703 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008704 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00008705
Steve Naroff090276f2008-10-10 01:28:17 +00008706 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00008707 }
John McCall7a9813c2010-01-22 00:28:27 +00008708 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008709}
8710
8711/// ActOnBlockError - If there is an error parsing a block, this callback
8712/// is invoked to pop the information about the block from the action impl.
8713void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00008714 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00008715 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008716 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008717}
8718
8719/// ActOnBlockStmtExpr - This is called when the body of a block statement
8720/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00008721ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00008722 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00008723 // If blocks are disabled, emit an error.
8724 if (!LangOpts.Blocks)
8725 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00008726
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008727 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008728
Steve Naroff090276f2008-10-10 01:28:17 +00008729 PopDeclContext();
8730
Steve Naroff4eb206b2008-09-03 18:15:37 +00008731 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00008732 if (!BSI->ReturnType.isNull())
8733 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008734
Mike Stump56925862009-07-28 22:04:01 +00008735 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008736 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00008737
John McCall469a1eb2011-02-02 13:00:07 +00008738 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00008739 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8740 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00008741
John McCallc71a4912010-06-04 19:02:56 +00008742 // If the user wrote a function type in some form, try to use that.
8743 if (!BSI->FunctionType.isNull()) {
8744 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8745
8746 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8747 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8748
8749 // Turn protoless block types into nullary block types.
8750 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00008751 FunctionProtoType::ExtProtoInfo EPI;
8752 EPI.ExtInfo = Ext;
8753 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008754
8755 // Otherwise, if we don't need to change anything about the function type,
8756 // preserve its sugar structure.
8757 } else if (FTy->getResultType() == RetTy &&
8758 (!NoReturn || FTy->getNoReturnAttr())) {
8759 BlockTy = BSI->FunctionType;
8760
8761 // Otherwise, make the minimal modifications to the function type.
8762 } else {
8763 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00008764 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8765 EPI.TypeQuals = 0; // FIXME: silently?
8766 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00008767 BlockTy = Context.getFunctionType(RetTy,
8768 FPT->arg_type_begin(),
8769 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00008770 EPI);
John McCallc71a4912010-06-04 19:02:56 +00008771 }
8772
8773 // If we don't have a function type, just build one from nothing.
8774 } else {
John McCalle23cf432010-12-14 08:05:40 +00008775 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00008776 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00008777 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008778 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008779
John McCallc71a4912010-06-04 19:02:56 +00008780 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8781 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00008782 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008783
Chris Lattner17a78302009-04-19 05:28:12 +00008784 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00008785 if (getCurFunction()->NeedsScopeChecking() &&
8786 !hasAnyUnrecoverableErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00008787 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00008788
Chris Lattnere476bdc2011-02-17 23:58:47 +00008789 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008790
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +00008791 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8792 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8793 const VarDecl *variable = ci->getVariable();
8794 QualType T = variable->getType();
8795 QualType::DestructionKind destructKind = T.isDestructedType();
8796 if (destructKind != QualType::DK_none)
8797 getCurFunction()->setHasBranchProtectedScope();
8798 }
8799
Douglas Gregorf8b7f712011-09-06 20:46:03 +00008800 computeNRVO(Body, getCurBlock());
8801
Benjamin Kramerd2486192011-07-12 14:11:05 +00008802 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8803 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8804 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8805
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008806 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00008807}
8808
John McCall60d7b3a2010-08-24 06:29:42 +00008809ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008810 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008811 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008812 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00008813 GetTypeFromParser(Ty, &TInfo);
8814 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008815}
8816
John McCall60d7b3a2010-08-24 06:29:42 +00008817ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00008818 Expr *E, TypeSourceInfo *TInfo,
8819 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008820 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00008821
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008822 // Get the va_list type
8823 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008824 if (VaListType->isArrayType()) {
8825 // Deal with implicit array decay; for example, on x86-64,
8826 // va_list is an array, but it's supposed to decay to
8827 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008828 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00008829 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00008830 ExprResult Result = UsualUnaryConversions(E);
8831 if (Result.isInvalid())
8832 return ExprError();
8833 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008834 } else {
8835 // Otherwise, the va_list argument must be an l-value because
8836 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00008837 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00008838 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00008839 return ExprError();
8840 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008841
Douglas Gregordd027302009-05-19 23:10:31 +00008842 if (!E->isTypeDependent() &&
8843 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00008844 return ExprError(Diag(E->getLocStart(),
8845 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008846 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00008847 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008848
David Majnemer0adde122011-06-14 05:17:32 +00008849 if (!TInfo->getType()->isDependentType()) {
8850 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8851 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8852 << TInfo->getTypeLoc().getSourceRange()))
8853 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00008854
David Majnemer0adde122011-06-14 05:17:32 +00008855 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8856 TInfo->getType(),
8857 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8858 << TInfo->getTypeLoc().getSourceRange()))
8859 return ExprError();
8860
Douglas Gregor4eb75222011-07-30 06:45:27 +00008861 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00008862 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00008863 TInfo->getType()->isObjCLifetimeType()
8864 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8865 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00008866 << TInfo->getType()
8867 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00008868 }
Eli Friedman46d37c12011-07-11 21:45:59 +00008869
8870 // Check for va_arg where arguments of the given type will be promoted
8871 // (i.e. this va_arg is guaranteed to have undefined behavior).
8872 QualType PromoteType;
8873 if (TInfo->getType()->isPromotableIntegerType()) {
8874 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8875 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8876 PromoteType = QualType();
8877 }
8878 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8879 PromoteType = Context.DoubleTy;
8880 if (!PromoteType.isNull())
8881 Diag(TInfo->getTypeLoc().getBeginLoc(),
8882 diag::warn_second_parameter_to_va_arg_never_compatible)
8883 << TInfo->getType()
8884 << PromoteType
8885 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00008886 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008887
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008888 QualType T = TInfo->getType().getNonLValueExprType(Context);
8889 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008890}
8891
John McCall60d7b3a2010-08-24 06:29:42 +00008892ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008893 // The type of __null will be int or long, depending on the size of
8894 // pointers on the target.
8895 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00008896 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
8897 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008898 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00008899 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008900 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00008901 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008902 Ty = Context.LongLongTy;
8903 else {
8904 assert(!"I don't know size of pointer!");
8905 Ty = Context.IntTy;
8906 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008907
Sebastian Redlf53597f2009-03-15 17:47:39 +00008908 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008909}
8910
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008911static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00008912 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008913 if (!SemaRef.getLangOptions().ObjC1)
8914 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008915
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008916 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8917 if (!PT)
8918 return;
8919
8920 // Check if the destination is of type 'id'.
8921 if (!PT->isObjCIdType()) {
8922 // Check if the destination is the 'NSString' interface.
8923 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8924 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8925 return;
8926 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008927
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008928 // Strip off any parens and casts.
8929 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregor5cee1192011-07-27 05:40:30 +00008930 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008931 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008932
Douglas Gregor849b2432010-03-31 17:46:05 +00008933 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008934}
8935
Chris Lattner5cf216b2008-01-04 18:04:52 +00008936bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8937 SourceLocation Loc,
8938 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00008939 Expr *SrcExpr, AssignmentAction Action,
8940 bool *Complained) {
8941 if (Complained)
8942 *Complained = false;
8943
Chris Lattner5cf216b2008-01-04 18:04:52 +00008944 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00008945 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008946 bool isInvalid = false;
8947 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00008948 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00008949 ConversionFixItGenerator ConvHints;
8950 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008951
Chris Lattner5cf216b2008-01-04 18:04:52 +00008952 switch (ConvTy) {
8953 default: assert(0 && "Unknown conversion type");
8954 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008955 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00008956 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00008957 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8958 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008959 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008960 case IntToPointer:
8961 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00008962 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8963 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008964 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008965 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00008966 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00008967 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00008968 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8969 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00008970 if (Hint.isNull() && !CheckInferredResultType) {
8971 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8972 }
8973 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008974 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00008975 case IncompatiblePointerSign:
8976 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8977 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008978 case FunctionVoidPointer:
8979 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8980 break;
John McCall86c05f32011-02-01 00:10:29 +00008981 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00008982 // Perform array-to-pointer decay if necessary.
8983 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8984
John McCall86c05f32011-02-01 00:10:29 +00008985 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8986 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8987 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8988 DiagKind = diag::err_typecheck_incompatible_address_space;
8989 break;
John McCallf85e1932011-06-15 23:02:42 +00008990
8991
8992 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008993 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00008994 break;
John McCall86c05f32011-02-01 00:10:29 +00008995 }
8996
8997 llvm_unreachable("unknown error case for discarding qualifiers!");
8998 // fallthrough
8999 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009000 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009001 // If the qualifiers lost were because we were applying the
9002 // (deprecated) C++ conversion from a string literal to a char*
9003 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9004 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009005 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009006 // bit of refactoring (so that the second argument is an
9007 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009008 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009009 // C++ semantics.
9010 if (getLangOptions().CPlusPlus &&
9011 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9012 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009013 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9014 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009015 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009016 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009017 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009018 case IntToBlockPointer:
9019 DiagKind = diag::err_int_to_block_pointer;
9020 break;
9021 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009022 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009023 break;
Steve Naroff39579072008-10-14 22:18:38 +00009024 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009025 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009026 // it can give a more specific diagnostic.
9027 DiagKind = diag::warn_incompatible_qualified_id;
9028 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009029 case IncompatibleVectors:
9030 DiagKind = diag::warn_incompatible_vectors;
9031 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00009032 case IncompatibleObjCWeakRef:
9033 DiagKind = diag::err_arc_weak_unavailable_assign;
9034 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009035 case Incompatible:
9036 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00009037 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9038 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009039 isInvalid = true;
9040 break;
9041 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009042
Douglas Gregord4eea832010-04-09 00:35:39 +00009043 QualType FirstType, SecondType;
9044 switch (Action) {
9045 case AA_Assigning:
9046 case AA_Initializing:
9047 // The destination type comes first.
9048 FirstType = DstType;
9049 SecondType = SrcType;
9050 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009051
Douglas Gregord4eea832010-04-09 00:35:39 +00009052 case AA_Returning:
9053 case AA_Passing:
9054 case AA_Converting:
9055 case AA_Sending:
9056 case AA_Casting:
9057 // The source type comes first.
9058 FirstType = SrcType;
9059 SecondType = DstType;
9060 break;
9061 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009062
Anna Zaks67221552011-07-28 19:51:27 +00009063 PartialDiagnostic FDiag = PDiag(DiagKind);
9064 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9065
9066 // If we can fix the conversion, suggest the FixIts.
9067 assert(ConvHints.isNull() || Hint.isNull());
9068 if (!ConvHints.isNull()) {
9069 for (llvm::SmallVector<FixItHint, 1>::iterator
9070 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
9071 HI != HE; ++HI)
9072 FDiag << *HI;
9073 } else {
9074 FDiag << Hint;
9075 }
9076 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9077
9078 Diag(Loc, FDiag);
9079
Douglas Gregor926df6c2011-06-11 01:09:30 +00009080 if (CheckInferredResultType)
9081 EmitRelatedResultTypeNote(SrcExpr);
9082
Douglas Gregora41a8c52010-04-22 00:20:18 +00009083 if (Complained)
9084 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009085 return isInvalid;
9086}
Anders Carlssone21555e2008-11-30 19:50:32 +00009087
Chris Lattner3bf68932009-04-25 21:59:05 +00009088bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009089 llvm::APSInt ICEResult;
9090 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9091 if (Result)
9092 *Result = ICEResult;
9093 return false;
9094 }
9095
Anders Carlssone21555e2008-11-30 19:50:32 +00009096 Expr::EvalResult EvalResult;
9097
Mike Stumpeed9cac2009-02-19 03:04:26 +00009098 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00009099 EvalResult.HasSideEffects) {
9100 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9101
9102 if (EvalResult.Diag) {
9103 // We only show the note if it's not the usual "invalid subexpression"
9104 // or if it's actually in a subexpression.
9105 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9106 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9107 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9108 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009109
Anders Carlssone21555e2008-11-30 19:50:32 +00009110 return true;
9111 }
9112
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009113 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9114 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00009115
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009116 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009117 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9118 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009119 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009120
Anders Carlssone21555e2008-11-30 19:50:32 +00009121 if (Result)
9122 *Result = EvalResult.Val.getInt();
9123 return false;
9124}
Douglas Gregore0762c92009-06-19 23:52:42 +00009125
Douglas Gregor2afce722009-11-26 00:44:06 +00009126void
Mike Stump1eb44332009-09-09 15:08:12 +00009127Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009128 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +00009129 ExpressionEvaluationContextRecord(NewContext,
9130 ExprTemporaries.size(),
9131 ExprNeedsCleanups));
9132 ExprNeedsCleanups = false;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009133}
9134
Richard Trieu67e29332011-08-02 04:35:43 +00009135void Sema::PopExpressionEvaluationContext() {
Douglas Gregor2afce722009-11-26 00:44:06 +00009136 // Pop the current expression evaluation context off the stack.
9137 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9138 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009139
Douglas Gregor06d33692009-12-12 07:57:52 +00009140 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9141 if (Rec.PotentiallyReferenced) {
9142 // Mark any remaining declarations in the current position of the stack
9143 // as "referenced". If they were not meant to be referenced, semantic
9144 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009145 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00009146 I = Rec.PotentiallyReferenced->begin(),
9147 IEnd = Rec.PotentiallyReferenced->end();
9148 I != IEnd; ++I)
9149 MarkDeclarationReferenced(I->first, I->second);
9150 }
9151
9152 if (Rec.PotentiallyDiagnosed) {
9153 // Emit any pending diagnostics.
9154 for (PotentiallyEmittedDiagnostics::iterator
9155 I = Rec.PotentiallyDiagnosed->begin(),
9156 IEnd = Rec.PotentiallyDiagnosed->end();
9157 I != IEnd; ++I)
9158 Diag(I->first, I->second);
9159 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009160 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009161
9162 // When are coming out of an unevaluated context, clear out any
9163 // temporaries that we may have created as part of the evaluation of
9164 // the expression in that context: they aren't relevant because they
9165 // will never be constructed.
John McCallf85e1932011-06-15 23:02:42 +00009166 if (Rec.Context == Unevaluated) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009167 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9168 ExprTemporaries.end());
John McCallf85e1932011-06-15 23:02:42 +00009169 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9170
9171 // Otherwise, merge the contexts together.
9172 } else {
9173 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9174 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009175
9176 // Destroy the popped expression evaluation record.
9177 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009178}
Douglas Gregore0762c92009-06-19 23:52:42 +00009179
John McCallf85e1932011-06-15 23:02:42 +00009180void Sema::DiscardCleanupsInEvaluationContext() {
9181 ExprTemporaries.erase(
9182 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9183 ExprTemporaries.end());
9184 ExprNeedsCleanups = false;
9185}
9186
Douglas Gregore0762c92009-06-19 23:52:42 +00009187/// \brief Note that the given declaration was referenced in the source code.
9188///
9189/// This routine should be invoke whenever a given declaration is referenced
9190/// in the source code, and where that reference occurred. If this declaration
9191/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9192/// C99 6.9p3), then the declaration will be marked as used.
9193///
9194/// \param Loc the location where the declaration was referenced.
9195///
9196/// \param D the declaration that has been referenced by the source code.
9197void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9198 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009199
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +00009200 D->setReferenced();
9201
Douglas Gregorc070cc62010-06-17 23:14:26 +00009202 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009203 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009204
Richard Trieu67e29332011-08-02 04:35:43 +00009205 // Mark a parameter or variable declaration "used", regardless of whether
9206 // we're in a template or not. The reason for this is that unevaluated
9207 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9208 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009209 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009210 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009211 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009212 return;
9213 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009214
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009215 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9216 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009217
Douglas Gregore0762c92009-06-19 23:52:42 +00009218 // Do not mark anything as "used" within a dependent context; wait for
9219 // an instantiation.
9220 if (CurContext->isDependentContext())
9221 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009222
Douglas Gregor2afce722009-11-26 00:44:06 +00009223 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009224 case Unevaluated:
9225 // We are in an expression that is not potentially evaluated; do nothing.
9226 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009227
Douglas Gregorac7610d2009-06-22 20:57:11 +00009228 case PotentiallyEvaluated:
9229 // We are in a potentially-evaluated expression, so this declaration is
9230 // "used"; handle this below.
9231 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009232
Douglas Gregorac7610d2009-06-22 20:57:11 +00009233 case PotentiallyPotentiallyEvaluated:
9234 // We are in an expression that may be potentially evaluated; queue this
9235 // declaration reference until we know whether the expression is
9236 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009237 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009238 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009239
9240 case PotentiallyEvaluatedIfUsed:
9241 // Referenced declarations will only be used if the construct in the
9242 // containing expression is used.
9243 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009244 }
Mike Stump1eb44332009-09-09 15:08:12 +00009245
Douglas Gregore0762c92009-06-19 23:52:42 +00009246 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009247 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009248 if (Constructor->isDefaulted()) {
9249 if (Constructor->isDefaultConstructor()) {
9250 if (Constructor->isTrivial())
9251 return;
9252 if (!Constructor->isUsed(false))
9253 DefineImplicitDefaultConstructor(Loc, Constructor);
9254 } else if (Constructor->isCopyConstructor()) {
9255 if (!Constructor->isUsed(false))
9256 DefineImplicitCopyConstructor(Loc, Constructor);
9257 } else if (Constructor->isMoveConstructor()) {
9258 if (!Constructor->isUsed(false))
9259 DefineImplicitMoveConstructor(Loc, Constructor);
9260 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009261 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009262
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009263 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009264 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00009265 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009266 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009267 if (Destructor->isVirtual())
9268 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009269 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Sean Hunt2b188082011-05-14 05:23:28 +00009270 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009271 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009272 if (!MethodDecl->isUsed(false)) {
9273 if (MethodDecl->isCopyAssignmentOperator())
9274 DefineImplicitCopyAssignment(Loc, MethodDecl);
9275 else
9276 DefineImplicitMoveAssignment(Loc, MethodDecl);
9277 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009278 } else if (MethodDecl->isVirtual())
9279 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009280 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009281 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +00009282 // Recursive functions should be marked when used from another function.
9283 if (CurContext == Function) return;
9284
Mike Stump1eb44332009-09-09 15:08:12 +00009285 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009286 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009287 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009288 bool AlreadyInstantiated = false;
9289 if (FunctionTemplateSpecializationInfo *SpecInfo
9290 = Function->getTemplateSpecializationInfo()) {
9291 if (SpecInfo->getPointOfInstantiation().isInvalid())
9292 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009293 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009294 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009295 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009296 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009297 = Function->getMemberSpecializationInfo()) {
9298 if (MSInfo->getPointOfInstantiation().isInvalid())
9299 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009300 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009301 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009302 AlreadyInstantiated = true;
9303 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009304
Douglas Gregor60406be2010-01-16 22:29:39 +00009305 if (!AlreadyInstantiated) {
9306 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9307 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9308 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9309 Loc));
9310 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00009311 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00009312 }
John McCall15e310a2011-02-19 02:53:41 +00009313 } else {
9314 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +00009315 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9316 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00009317 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00009318 MarkDeclarationReferenced(Loc, *i);
9319 }
John McCall15e310a2011-02-19 02:53:41 +00009320 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009321
John McCall15e310a2011-02-19 02:53:41 +00009322 // Keep track of used but undefined functions.
9323 if (!Function->isPure() && !Function->hasBody() &&
9324 Function->getLinkage() != ExternalLinkage) {
9325 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9326 if (old.isInvalid()) old = Loc;
9327 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00009328
John McCall15e310a2011-02-19 02:53:41 +00009329 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +00009330 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009331 }
Mike Stump1eb44332009-09-09 15:08:12 +00009332
Douglas Gregore0762c92009-06-19 23:52:42 +00009333 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00009334 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00009335 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009336 Var->getInstantiatedFromStaticDataMember()) {
9337 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9338 assert(MSInfo && "Missing member specialization information?");
9339 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9340 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9341 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redlf79a7192011-04-29 08:19:30 +00009342 // This is a modification of an existing AST node. Notify listeners.
9343 if (ASTMutationListener *L = getASTMutationListener())
9344 L->StaticDataMemberInstantiated(Var);
Chandler Carruth62c78d52010-08-25 08:44:16 +00009345 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009346 }
9347 }
Mike Stump1eb44332009-09-09 15:08:12 +00009348
John McCall77efc682011-02-21 19:25:48 +00009349 // Keep track of used but undefined variables. We make a hole in
9350 // the warning for static const data members with in-line
9351 // initializers.
John McCall15e310a2011-02-19 02:53:41 +00009352 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall77efc682011-02-21 19:25:48 +00009353 && Var->getLinkage() != ExternalLinkage
9354 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall15e310a2011-02-19 02:53:41 +00009355 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9356 if (old.isInvalid()) old = Loc;
9357 }
Douglas Gregor7caa6822009-07-24 20:34:43 +00009358
Douglas Gregore0762c92009-06-19 23:52:42 +00009359 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00009360 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00009361 }
Douglas Gregore0762c92009-06-19 23:52:42 +00009362}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009363
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009364namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009365 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009366 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009367 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009368 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9369 Sema &S;
9370 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009371
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009372 public:
9373 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009374
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009375 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009376
9377 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9378 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009379 };
9380}
9381
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009382bool MarkReferencedDecls::TraverseTemplateArgument(
9383 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009384 if (Arg.getKind() == TemplateArgument::Declaration) {
9385 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9386 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009387
9388 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009389}
9390
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009391bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009392 if (ClassTemplateSpecializationDecl *Spec
9393 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9394 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +00009395 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009396 }
9397
Chandler Carruthe3e210c2010-06-10 10:31:57 +00009398 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009399}
9400
9401void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9402 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009403 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009404}
9405
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009406namespace {
9407 /// \brief Helper class that marks all of the declarations referenced by
9408 /// potentially-evaluated subexpressions as "referenced".
9409 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9410 Sema &S;
9411
9412 public:
9413 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9414
9415 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9416
9417 void VisitDeclRefExpr(DeclRefExpr *E) {
9418 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9419 }
9420
9421 void VisitMemberExpr(MemberExpr *E) {
9422 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009423 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009424 }
9425
9426 void VisitCXXNewExpr(CXXNewExpr *E) {
9427 if (E->getConstructor())
9428 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9429 if (E->getOperatorNew())
9430 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9431 if (E->getOperatorDelete())
9432 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009433 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009434 }
9435
9436 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9437 if (E->getOperatorDelete())
9438 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +00009439 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9440 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9441 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9442 S.MarkDeclarationReferenced(E->getLocStart(),
9443 S.LookupDestructor(Record));
9444 }
9445
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009446 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009447 }
9448
9449 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9450 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009451 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009452 }
9453
9454 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9455 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9456 }
Douglas Gregor102ff972010-10-19 17:17:35 +00009457
9458 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9459 Visit(E->getExpr());
9460 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009461 };
9462}
9463
9464/// \brief Mark any declarations that appear within this expression or any
9465/// potentially-evaluated subexpressions as "referenced".
9466void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9467 EvaluatedExprMarker(*this).Visit(E);
9468}
9469
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009470/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9471/// of the program being compiled.
9472///
9473/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009474/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009475/// possibility that the code will actually be executable. Code in sizeof()
9476/// expressions, code used only during overload resolution, etc., are not
9477/// potentially evaluated. This routine will suppress such diagnostics or,
9478/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009479/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009480/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009481///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009482/// This routine should be used for all diagnostics that describe the run-time
9483/// behavior of a program, such as passing a non-POD value through an ellipsis.
9484/// Failure to do so will likely result in spurious diagnostics or failures
9485/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +00009486bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009487 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +00009488 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009489 case Unevaluated:
9490 // The argument will never be evaluated, so don't complain.
9491 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009492
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009493 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009494 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +00009495 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00009496 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +00009497 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +00009498 }
9499 else
9500 Diag(Loc, PD);
9501
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009502 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009503
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009504 case PotentiallyPotentiallyEvaluated:
9505 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9506 break;
9507 }
9508
9509 return false;
9510}
9511
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009512bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9513 CallExpr *CE, FunctionDecl *FD) {
9514 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9515 return false;
9516
9517 PartialDiagnostic Note =
9518 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9519 << FD->getDeclName() : PDiag();
9520 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009521
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009522 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009523 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009524 PDiag(diag::err_call_function_incomplete_return)
9525 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009526 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009527 << CE->getSourceRange(),
9528 std::make_pair(NoteLoc, Note)))
9529 return true;
9530
9531 return false;
9532}
9533
Douglas Gregor92c3a042011-01-19 16:50:08 +00009534// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +00009535// will prevent this condition from triggering, which is what we want.
9536void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9537 SourceLocation Loc;
9538
John McCalla52ef082009-11-11 02:41:58 +00009539 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +00009540 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +00009541
Chandler Carruthb33c19f2011-08-16 22:30:10 +00009542 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +00009543 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +00009544 return;
9545
Douglas Gregor92c3a042011-01-19 16:50:08 +00009546 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9547
John McCallc8d8ac52009-11-12 00:06:05 +00009548 // Greylist some idioms by putting them into a warning subcategory.
9549 if (ObjCMessageExpr *ME
9550 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9551 Selector Sel = ME->getSelector();
9552
John McCallc8d8ac52009-11-12 00:06:05 +00009553 // self = [<foo> init...]
Douglas Gregor813d8342011-02-18 22:29:55 +00009554 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +00009555 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9556
9557 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +00009558 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +00009559 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9560 }
John McCalla52ef082009-11-11 02:41:58 +00009561
John McCall5a881bb2009-10-12 21:59:07 +00009562 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +00009563 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +00009564 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +00009565 return;
9566
Douglas Gregor92c3a042011-01-19 16:50:08 +00009567 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +00009568 Loc = Op->getOperatorLoc();
9569 } else {
9570 // Not an assignment.
9571 return;
9572 }
9573
Douglas Gregor55b38842010-04-14 16:09:52 +00009574 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +00009575
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009576 SourceLocation Open = E->getSourceRange().getBegin();
9577 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9578 Diag(Loc, diag::note_condition_assign_silence)
9579 << FixItHint::CreateInsertion(Open, "(")
9580 << FixItHint::CreateInsertion(Close, ")");
9581
Douglas Gregor92c3a042011-01-19 16:50:08 +00009582 if (IsOrAssign)
9583 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9584 << FixItHint::CreateReplacement(Loc, "!=");
9585 else
9586 Diag(Loc, diag::note_condition_assign_to_comparison)
9587 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +00009588}
9589
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009590/// \brief Redundant parentheses over an equality comparison can indicate
9591/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +00009592void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009593 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +00009594 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009595 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9596 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +00009597 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00009598 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +00009599 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009600
Richard Trieuccd891a2011-09-09 01:45:06 +00009601 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009602
9603 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +00009604 if (opE->getOpcode() == BO_EQ &&
9605 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9606 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009607 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +00009608
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009609 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009610 Diag(Loc, diag::note_equality_comparison_silence)
Richard Trieuccd891a2011-09-09 01:45:06 +00009611 << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin())
9612 << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009613 Diag(Loc, diag::note_equality_comparison_to_assign)
9614 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009615 }
9616}
9617
John Wiegley429bb272011-04-08 18:41:53 +00009618ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +00009619 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009620 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9621 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +00009622
John McCall864c0412011-04-26 20:42:42 +00009623 ExprResult result = CheckPlaceholderExpr(E);
9624 if (result.isInvalid()) return ExprError();
9625 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00009626
John McCall864c0412011-04-26 20:42:42 +00009627 if (!E->isTypeDependent()) {
John McCallf6a16482010-12-04 03:47:34 +00009628 if (getLangOptions().CPlusPlus)
9629 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9630
John Wiegley429bb272011-04-08 18:41:53 +00009631 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9632 if (ERes.isInvalid())
9633 return ExprError();
9634 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +00009635
9636 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +00009637 if (!T->isScalarType()) { // C99 6.8.4.1p1
9638 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9639 << T << E->getSourceRange();
9640 return ExprError();
9641 }
John McCall5a881bb2009-10-12 21:59:07 +00009642 }
9643
John Wiegley429bb272011-04-08 18:41:53 +00009644 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +00009645}
Douglas Gregor586596f2010-05-06 17:25:47 +00009646
John McCall60d7b3a2010-08-24 06:29:42 +00009647ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009648 Expr *SubExpr) {
9649 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +00009650 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009651
Richard Trieuccd891a2011-09-09 01:45:06 +00009652 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +00009653}
John McCall2a984ca2010-10-12 00:20:44 +00009654
John McCall1de4d4e2011-04-07 08:22:57 +00009655namespace {
John McCall755d8492011-04-12 00:42:48 +00009656 /// A visitor for rebuilding a call to an __unknown_any expression
9657 /// to have an appropriate type.
9658 struct RebuildUnknownAnyFunction
9659 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9660
9661 Sema &S;
9662
9663 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9664
9665 ExprResult VisitStmt(Stmt *S) {
9666 llvm_unreachable("unexpected statement!");
9667 return ExprError();
9668 }
9669
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009670 ExprResult VisitExpr(Expr *E) {
9671 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
9672 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +00009673 return ExprError();
9674 }
9675
9676 /// Rebuild an expression which simply semantically wraps another
9677 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009678 template <class T> ExprResult rebuildSugarExpr(T *E) {
9679 ExprResult SubResult = Visit(E->getSubExpr());
9680 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +00009681
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009682 Expr *SubExpr = SubResult.take();
9683 E->setSubExpr(SubExpr);
9684 E->setType(SubExpr->getType());
9685 E->setValueKind(SubExpr->getValueKind());
9686 assert(E->getObjectKind() == OK_Ordinary);
9687 return E;
John McCall755d8492011-04-12 00:42:48 +00009688 }
9689
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009690 ExprResult VisitParenExpr(ParenExpr *E) {
9691 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +00009692 }
9693
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009694 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9695 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +00009696 }
9697
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009698 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9699 ExprResult SubResult = Visit(E->getSubExpr());
9700 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +00009701
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009702 Expr *SubExpr = SubResult.take();
9703 E->setSubExpr(SubExpr);
9704 E->setType(S.Context.getPointerType(SubExpr->getType()));
9705 assert(E->getValueKind() == VK_RValue);
9706 assert(E->getObjectKind() == OK_Ordinary);
9707 return E;
John McCall755d8492011-04-12 00:42:48 +00009708 }
9709
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009710 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
9711 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +00009712
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009713 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +00009714
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009715 assert(E->getValueKind() == VK_RValue);
John McCall755d8492011-04-12 00:42:48 +00009716 if (S.getLangOptions().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009717 !(isa<CXXMethodDecl>(VD) &&
9718 cast<CXXMethodDecl>(VD)->isInstance()))
9719 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +00009720
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009721 return E;
John McCall755d8492011-04-12 00:42:48 +00009722 }
9723
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009724 ExprResult VisitMemberExpr(MemberExpr *E) {
9725 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +00009726 }
9727
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009728 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9729 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +00009730 }
9731 };
9732}
9733
9734/// Given a function expression of unknown-any type, try to rebuild it
9735/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009736static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
9737 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
9738 if (Result.isInvalid()) return ExprError();
9739 return S.DefaultFunctionArrayConversion(Result.take());
John McCall755d8492011-04-12 00:42:48 +00009740}
9741
9742namespace {
John McCall379b5152011-04-11 07:02:50 +00009743 /// A visitor for rebuilding an expression of type __unknown_anytype
9744 /// into one which resolves the type directly on the referring
9745 /// expression. Strict preservation of the original source
9746 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +00009747 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +00009748 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +00009749
9750 Sema &S;
9751
9752 /// The current destination type.
9753 QualType DestType;
9754
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009755 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
9756 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +00009757
John McCalla5fc4722011-04-09 22:50:59 +00009758 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +00009759 llvm_unreachable("unexpected statement!");
John McCalla5fc4722011-04-09 22:50:59 +00009760 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009761 }
9762
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009763 ExprResult VisitExpr(Expr *E) {
9764 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9765 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +00009766 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009767 }
9768
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009769 ExprResult VisitCallExpr(CallExpr *E);
9770 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +00009771
John McCalla5fc4722011-04-09 22:50:59 +00009772 /// Rebuild an expression which simply semantically wraps another
9773 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009774 template <class T> ExprResult rebuildSugarExpr(T *E) {
9775 ExprResult SubResult = Visit(E->getSubExpr());
9776 if (SubResult.isInvalid()) return ExprError();
9777 Expr *SubExpr = SubResult.take();
9778 E->setSubExpr(SubExpr);
9779 E->setType(SubExpr->getType());
9780 E->setValueKind(SubExpr->getValueKind());
9781 assert(E->getObjectKind() == OK_Ordinary);
9782 return E;
John McCalla5fc4722011-04-09 22:50:59 +00009783 }
John McCall1de4d4e2011-04-07 08:22:57 +00009784
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009785 ExprResult VisitParenExpr(ParenExpr *E) {
9786 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +00009787 }
9788
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009789 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9790 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +00009791 }
9792
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009793 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9794 const PointerType *Ptr = DestType->getAs<PointerType>();
9795 if (!Ptr) {
9796 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
9797 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +00009798 return ExprError();
9799 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009800 assert(E->getValueKind() == VK_RValue);
9801 assert(E->getObjectKind() == OK_Ordinary);
9802 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +00009803
9804 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009805 DestType = Ptr->getPointeeType();
9806 ExprResult SubResult = Visit(E->getSubExpr());
9807 if (SubResult.isInvalid()) return ExprError();
9808 E->setSubExpr(SubResult.take());
9809 return E;
John McCall755d8492011-04-12 00:42:48 +00009810 }
9811
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009812 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +00009813
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009814 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +00009815
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009816 ExprResult VisitMemberExpr(MemberExpr *E) {
9817 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +00009818 }
John McCalla5fc4722011-04-09 22:50:59 +00009819
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009820 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9821 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +00009822 }
9823 };
9824}
9825
John McCall379b5152011-04-11 07:02:50 +00009826/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009827ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
9828 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +00009829
9830 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +00009831 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +00009832 FK_FunctionPointer,
9833 FK_BlockPointer
9834 };
9835
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009836 FnKind Kind;
9837 QualType CalleeType = CalleeExpr->getType();
9838 if (CalleeType == S.Context.BoundMemberTy) {
9839 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
9840 Kind = FK_MemberFunction;
9841 CalleeType = Expr::findBoundMemberType(CalleeExpr);
9842 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
9843 CalleeType = Ptr->getPointeeType();
9844 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +00009845 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009846 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
9847 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +00009848 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009849 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +00009850
9851 // Verify that this is a legal result type of a function.
9852 if (DestType->isArrayType() || DestType->isFunctionType()) {
9853 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009854 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +00009855 diagID = diag::err_block_returning_array_function;
9856
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009857 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +00009858 << DestType->isFunctionType() << DestType;
9859 return ExprError();
9860 }
9861
9862 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009863 E->setType(DestType.getNonLValueExprType(S.Context));
9864 E->setValueKind(Expr::getValueKindForType(DestType));
9865 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +00009866
9867 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009868 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall379b5152011-04-11 07:02:50 +00009869 DestType = S.Context.getFunctionType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009870 Proto->arg_type_begin(),
9871 Proto->getNumArgs(),
9872 Proto->getExtProtoInfo());
John McCall379b5152011-04-11 07:02:50 +00009873 else
9874 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009875 FnType->getExtInfo());
John McCall379b5152011-04-11 07:02:50 +00009876
9877 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009878 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +00009879 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +00009880 // Nothing to do.
9881 break;
9882
9883 case FK_FunctionPointer:
9884 DestType = S.Context.getPointerType(DestType);
9885 break;
9886
9887 case FK_BlockPointer:
9888 DestType = S.Context.getBlockPointerType(DestType);
9889 break;
9890 }
9891
9892 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009893 ExprResult CalleeResult = Visit(CalleeExpr);
9894 if (!CalleeResult.isUsable()) return ExprError();
9895 E->setCallee(CalleeResult.take());
John McCall379b5152011-04-11 07:02:50 +00009896
9897 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009898 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +00009899}
9900
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009901ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +00009902 // Verify that this is a legal result type of a call.
9903 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009904 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +00009905 << DestType->isFunctionType() << DestType;
9906 return ExprError();
John McCall379b5152011-04-11 07:02:50 +00009907 }
9908
John McCall48218c62011-07-13 17:56:40 +00009909 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009910 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
9911 assert(Method->getResultType() == S.Context.UnknownAnyTy);
9912 Method->setResultType(DestType);
John McCall48218c62011-07-13 17:56:40 +00009913 }
John McCall755d8492011-04-12 00:42:48 +00009914
John McCall379b5152011-04-11 07:02:50 +00009915 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009916 E->setType(DestType.getNonReferenceType());
9917 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +00009918
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009919 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +00009920}
9921
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009922ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +00009923 // The only case we should ever see here is a function-to-pointer decay.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009924 assert(E->getCastKind() == CK_FunctionToPointerDecay);
9925 assert(E->getValueKind() == VK_RValue);
9926 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +00009927
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009928 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +00009929
John McCall379b5152011-04-11 07:02:50 +00009930 // Rebuild the sub-expression as the pointee (function) type.
9931 DestType = DestType->castAs<PointerType>()->getPointeeType();
9932
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009933 ExprResult Result = Visit(E->getSubExpr());
9934 if (!Result.isUsable()) return ExprError();
John McCall379b5152011-04-11 07:02:50 +00009935
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009936 E->setSubExpr(Result.take());
9937 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +00009938}
9939
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009940ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
9941 ExprValueKind ValueKind = VK_LValue;
9942 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +00009943
9944 // We know how to make this work for certain kinds of decls:
9945
9946 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009947 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
9948 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
9949 DestType = Ptr->getPointeeType();
9950 ExprResult Result = resolveDecl(E, VD);
9951 if (Result.isInvalid()) return ExprError();
9952 return S.ImpCastExprToType(Result.take(), Type,
John McCalla19950e2011-08-10 04:12:23 +00009953 CK_FunctionToPointerDecay, VK_RValue);
9954 }
9955
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009956 if (!Type->isFunctionType()) {
9957 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
9958 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +00009959 return ExprError();
9960 }
John McCall379b5152011-04-11 07:02:50 +00009961
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009962 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
9963 if (MD->isInstance()) {
9964 ValueKind = VK_RValue;
9965 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +00009966 }
9967
John McCall379b5152011-04-11 07:02:50 +00009968 // Function references aren't l-values in C.
9969 if (!S.getLangOptions().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009970 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +00009971
9972 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009973 } else if (isa<VarDecl>(VD)) {
9974 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
9975 Type = RefTy->getPointeeType();
9976 } else if (Type->isFunctionType()) {
9977 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
9978 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +00009979 return ExprError();
John McCall379b5152011-04-11 07:02:50 +00009980 }
9981
9982 // - nothing else
9983 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009984 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9985 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +00009986 return ExprError();
9987 }
9988
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009989 VD->setType(DestType);
9990 E->setType(Type);
9991 E->setValueKind(ValueKind);
9992 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +00009993}
9994
John McCall1de4d4e2011-04-07 08:22:57 +00009995/// Check a cast of an unknown-any type. We intentionally only
9996/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +00009997ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9998 Expr *CastExpr, CastKind &CastKind,
9999 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000010000 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000010001 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000010002 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010003
Richard Trieuccd891a2011-09-09 01:45:06 +000010004 CastExpr = result.take();
10005 VK = CastExpr->getValueKind();
10006 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000010007
Richard Trieuccd891a2011-09-09 01:45:06 +000010008 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000010009}
10010
Richard Trieuccd891a2011-09-09 01:45:06 +000010011static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
10012 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000010013 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000010014 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000010015 E = E->IgnoreParenImpCasts();
10016 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
10017 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000010018 diagID = diag::err_uncasted_call_of_unknown_any;
10019 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000010020 break;
John McCall379b5152011-04-11 07:02:50 +000010021 }
John McCall1de4d4e2011-04-07 08:22:57 +000010022 }
10023
John McCall379b5152011-04-11 07:02:50 +000010024 SourceLocation loc;
10025 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000010026 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000010027 loc = ref->getLocation();
10028 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000010029 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000010030 loc = mem->getMemberLoc();
10031 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000010032 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000010033 diagID = diag::err_uncasted_call_of_unknown_any;
10034 loc = msg->getSelectorLoc();
10035 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000010036 if (!d) {
10037 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
10038 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
10039 << orig->getSourceRange();
10040 return ExprError();
10041 }
John McCall379b5152011-04-11 07:02:50 +000010042 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000010043 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10044 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000010045 return ExprError();
10046 }
10047
10048 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000010049
10050 // Never recoverable.
10051 return ExprError();
10052}
10053
John McCall2a984ca2010-10-12 00:20:44 +000010054/// Check for operands with placeholder types and complain if found.
10055/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000010056ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall1de4d4e2011-04-07 08:22:57 +000010057 // Placeholder types are always *exactly* the appropriate builtin type.
10058 QualType type = E->getType();
John McCall2a984ca2010-10-12 00:20:44 +000010059
John McCall1de4d4e2011-04-07 08:22:57 +000010060 // Overloaded expressions.
10061 if (type == Context.OverloadTy)
10062 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregordb2eae62011-03-16 19:16:25 +000010063 E->getSourceRange(),
John McCall1de4d4e2011-04-07 08:22:57 +000010064 QualType(),
10065 diag::err_ovl_unresolvable);
10066
John McCall864c0412011-04-26 20:42:42 +000010067 // Bound member functions.
10068 if (type == Context.BoundMemberTy) {
10069 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10070 << E->getSourceRange();
10071 return ExprError();
10072 }
10073
John McCall1de4d4e2011-04-07 08:22:57 +000010074 // Expressions of unknown type.
10075 if (type == Context.UnknownAnyTy)
10076 return diagnoseUnknownAnyExpr(*this, E);
10077
10078 assert(!type->isPlaceholderType());
10079 return Owned(E);
John McCall2a984ca2010-10-12 00:20:44 +000010080}
Richard Trieubb9b80c2011-04-21 21:44:26 +000010081
Richard Trieuccd891a2011-09-09 01:45:06 +000010082bool Sema::CheckCaseExpression(Expr *E) {
10083 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000010084 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000010085 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
10086 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000010087 return false;
10088}