blob: 0fea54b77dc30b80b24f21e3613ff5f8c094730d [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
Sebastian Redl14b0c192011-09-24 17:48:00 +000044/// \brief Determine whether the use of this declaration is valid, without
45/// emitting diagnostics.
46bool Sema::CanUseDecl(NamedDecl *D) {
47 // See if this is an auto-typed variable whose initializer we are parsing.
48 if (ParsingInitForAutoVars.count(D))
49 return false;
50
51 // See if this is a deleted function.
52 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
53 if (FD->isDeleted())
54 return false;
55 }
56 return true;
57}
David Chisnall0f436562009-08-17 16:35:33 +000058
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000059static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
60 NamedDecl *D, SourceLocation Loc,
61 const ObjCInterfaceDecl *UnknownObjCClass) {
62 // See if this declaration is unavailable or deprecated.
63 std::string Message;
64 AvailabilityResult Result = D->getAvailability(&Message);
65 switch (Result) {
66 case AR_Available:
67 case AR_NotYetIntroduced:
68 break;
69
70 case AR_Deprecated:
71 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
72 break;
73
74 case AR_Unavailable:
75 if (cast<Decl>(S.CurContext)->getAvailability() != AR_Unavailable) {
76 if (Message.empty()) {
77 if (!UnknownObjCClass)
78 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
79 else
80 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
81 << D->getDeclName();
82 }
83 else
84 S.Diag(Loc, diag::err_unavailable_message)
85 << D->getDeclName() << Message;
86 S.Diag(D->getLocation(), diag::note_unavailable_here)
87 << isa<FunctionDecl>(D) << false;
88 }
89 break;
90 }
91 return Result;
92}
93
Douglas Gregor48f3bb92009-02-18 21:56:37 +000094/// \brief Determine whether the use of this declaration is valid, and
95/// emit any corresponding diagnostics.
96///
97/// This routine diagnoses various problems with referencing
98/// declarations that can occur when using a declaration. For example,
99/// it might warn if a deprecated or unavailable declaration is being
100/// used, or produce an error (and return true) if a C++0x deleted
101/// function is being used.
102///
103/// \returns true if there was an error (this declaration cannot be
104/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +0000105///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +0000106bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000107 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor9b623632010-10-12 23:32:35 +0000108 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
109 // If there were any diagnostics suppressed by template argument deduction,
110 // emit them now.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000111 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +0000112 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
113 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000114 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor9b623632010-10-12 23:32:35 +0000115 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
116 Diag(Suppressed[I].first, Suppressed[I].second);
117
118 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000119 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +0000120 // entry from the table, because we want to avoid ever emitting these
121 // diagnostics again.
122 Suppressed.clear();
123 }
124 }
125
Richard Smith34b41d92011-02-20 03:19:35 +0000126 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +0000127 if (ParsingInitForAutoVars.count(D)) {
128 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
129 << D->getDeclName();
130 return true;
Richard Smith34b41d92011-02-20 03:19:35 +0000131 }
132
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000133 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +0000134 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000135 if (FD->isDeleted()) {
136 Diag(Loc, diag::err_deleted_function_use);
John McCallf85e1932011-06-15 23:02:42 +0000137 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000138 return true;
139 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000140 }
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000141 AvailabilityResult Result =
142 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000143
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000144 // Warn if this is used but marked unused.
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000145 if (D->hasAttr<UnusedAttr>())
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000146 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
Fariborz Jahanian97db7262011-09-29 18:40:01 +0000147 // For available enumerator, it will become unavailable/deprecated
148 // if its enum declaration is as such.
149 if (Result == AR_Available)
150 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
151 const DeclContext *DC = ECD->getDeclContext();
152 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000153 DiagnoseAvailabilityOfDecl(*this,
154 const_cast< EnumDecl *>(TheEnumDecl),
155 Loc, UnknownObjCClass);
Fariborz Jahanian97db7262011-09-29 18:40:01 +0000156 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000157 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000158}
159
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000160/// \brief Retrieve the message suffix that should be added to a
161/// diagnostic complaining about the given function being deleted or
162/// unavailable.
163std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
164 // FIXME: C++0x implicitly-deleted special member functions could be
165 // detected here so that we could improve diagnostics to say, e.g.,
166 // "base class 'A' had a deleted copy constructor".
167 if (FD->isDeleted())
168 return std::string();
169
170 std::string Message;
171 if (FD->getAvailability(&Message))
172 return ": " + Message;
173
174 return std::string();
175}
176
John McCall3323fad2011-09-09 07:56:05 +0000177/// DiagnoseSentinelCalls - This routine checks whether a call or
178/// message-send is to a declaration with the sentinel attribute, and
179/// if so, it checks that the requirements of the sentinel are
180/// satisfied.
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000181void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCall3323fad2011-09-09 07:56:05 +0000182 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000183 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000184 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000185 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000186
John McCall3323fad2011-09-09 07:56:05 +0000187 // The number of formal parameters of the declaration.
188 unsigned numFormalParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000189
John McCall3323fad2011-09-09 07:56:05 +0000190 // The kind of declaration. This is also an index into a %select in
191 // the diagnostic.
192 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
193
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000194 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000195 numFormalParams = MD->param_size();
196 calleeType = CT_Method;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000197 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000198 numFormalParams = FD->param_size();
199 calleeType = CT_Function;
200 } else if (isa<VarDecl>(D)) {
201 QualType type = cast<ValueDecl>(D)->getType();
202 const FunctionType *fn = 0;
203 if (const PointerType *ptr = type->getAs<PointerType>()) {
204 fn = ptr->getPointeeType()->getAs<FunctionType>();
205 if (!fn) return;
206 calleeType = CT_Function;
207 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
208 fn = ptr->getPointeeType()->castAs<FunctionType>();
209 calleeType = CT_Block;
210 } else {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000211 return;
John McCall3323fad2011-09-09 07:56:05 +0000212 }
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000213
John McCall3323fad2011-09-09 07:56:05 +0000214 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
215 numFormalParams = proto->getNumArgs();
216 } else {
217 numFormalParams = 0;
218 }
219 } else {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000220 return;
221 }
John McCall3323fad2011-09-09 07:56:05 +0000222
223 // "nullPos" is the number of formal parameters at the end which
224 // effectively count as part of the variadic arguments. This is
225 // useful if you would prefer to not have *any* formal parameters,
226 // but the language forces you to have at least one.
227 unsigned nullPos = attr->getNullPos();
228 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
229 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
230
231 // The number of arguments which should follow the sentinel.
232 unsigned numArgsAfterSentinel = attr->getSentinel();
233
234 // If there aren't enough arguments for all the formal parameters,
235 // the sentinel, and the args after the sentinel, complain.
236 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000237 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCall3323fad2011-09-09 07:56:05 +0000238 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000239 return;
240 }
John McCall3323fad2011-09-09 07:56:05 +0000241
242 // Otherwise, find the sentinel expression.
243 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall8eb662e2010-05-06 23:53:00 +0000244 if (!sentinelExpr) return;
John McCall8eb662e2010-05-06 23:53:00 +0000245 if (sentinelExpr->isValueDependent()) return;
Anders Carlsson343e6ff2010-11-05 15:21:33 +0000246
247 // nullptr_t is always treated as null.
248 if (sentinelExpr->getType()->isNullPtrType()) return;
249
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000250 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-05-06 23:53:00 +0000251 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
252 Expr::NPC_ValueDependentIsNull))
253 return;
254
255 // Unfortunately, __null has type 'int'.
256 if (isa<GNUNullExpr>(sentinelExpr)) return;
257
John McCall3323fad2011-09-09 07:56:05 +0000258 // Pick a reasonable string to insert. Optimistically use 'nil' or
259 // 'NULL' if those are actually defined in the context. Only use
260 // 'nil' for ObjC methods, where it's much more likely that the
261 // variadic arguments form a list of object pointers.
262 SourceLocation MissingNilLoc
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000263 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
264 std::string NullValue;
John McCall3323fad2011-09-09 07:56:05 +0000265 if (calleeType == CT_Method &&
266 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000267 NullValue = "nil";
268 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
269 NullValue = "NULL";
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000270 else
John McCall3323fad2011-09-09 07:56:05 +0000271 NullValue = "(void*) 0";
Eli Friedman39834ba2011-09-27 23:46:37 +0000272
273 if (MissingNilLoc.isInvalid())
274 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
275 else
276 Diag(MissingNilLoc, diag::warn_missing_sentinel)
277 << calleeType
278 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall3323fad2011-09-09 07:56:05 +0000279 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000280}
281
Richard Trieuccd891a2011-09-09 01:45:06 +0000282SourceRange Sema::getExprRange(Expr *E) const {
283 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000284}
285
Chris Lattnere7a2e912008-07-25 21:10:04 +0000286//===----------------------------------------------------------------------===//
287// Standard Promotions and Conversions
288//===----------------------------------------------------------------------===//
289
Chris Lattnere7a2e912008-07-25 21:10:04 +0000290/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000291ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000292 QualType Ty = E->getType();
293 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
294
Chris Lattnere7a2e912008-07-25 21:10:04 +0000295 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000296 E = ImpCastExprToType(E, Context.getPointerType(Ty),
297 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000298 else if (Ty->isArrayType()) {
299 // In C90 mode, arrays only promote to pointers if the array expression is
300 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
301 // type 'array of type' is converted to an expression that has type 'pointer
302 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
303 // that has type 'array of type' ...". The relevant change is "an lvalue"
304 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000305 //
306 // C++ 4.2p1:
307 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
308 // T" can be converted to an rvalue of type "pointer to T".
309 //
John McCall7eb0a9e2010-11-24 05:12:34 +0000310 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000311 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
312 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000313 }
John Wiegley429bb272011-04-08 18:41:53 +0000314 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000315}
316
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000317static void CheckForNullPointerDereference(Sema &S, Expr *E) {
318 // Check to see if we are dereferencing a null pointer. If so,
319 // and if not volatile-qualified, this is undefined behavior that the
320 // optimizer will delete, so warn about it. People sometimes try to use this
321 // to get a deterministic trap and are surprised by clang's behavior. This
322 // only handles the pattern "*null", which is a very syntactic check.
323 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
324 if (UO->getOpcode() == UO_Deref &&
325 UO->getSubExpr()->IgnoreParenCasts()->
326 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
327 !UO->getType().isVolatileQualified()) {
328 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
329 S.PDiag(diag::warn_indirection_through_null)
330 << UO->getSubExpr()->getSourceRange());
331 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
332 S.PDiag(diag::note_indirection_through_null));
333 }
334}
335
John Wiegley429bb272011-04-08 18:41:53 +0000336ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000337 // C++ [conv.lval]p1:
338 // A glvalue of a non-function, non-array type T can be
339 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000340 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000341
John McCall409fa9a2010-12-06 20:48:59 +0000342 QualType T = E->getType();
343 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000344
John McCall409fa9a2010-12-06 20:48:59 +0000345 // Create a load out of an ObjCProperty l-value, if necessary.
346 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +0000347 ExprResult Res = ConvertPropertyForRValue(E);
348 if (Res.isInvalid())
349 return Owned(E);
350 E = Res.take();
John McCall409fa9a2010-12-06 20:48:59 +0000351 if (!E->isGLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000352 return Owned(E);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000353 }
John McCall409fa9a2010-12-06 20:48:59 +0000354
355 // We don't want to throw lvalue-to-rvalue casts on top of
356 // expressions of certain types in C++.
357 if (getLangOptions().CPlusPlus &&
358 (E->getType() == Context.OverloadTy ||
359 T->isDependentType() ||
360 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000361 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000362
363 // The C standard is actually really unclear on this point, and
364 // DR106 tells us what the result should be but not why. It's
365 // generally best to say that void types just doesn't undergo
366 // lvalue-to-rvalue at all. Note that expressions of unqualified
367 // 'void' type are never l-values, but qualified void can be.
368 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000369 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000370
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000371 CheckForNullPointerDereference(*this, E);
372
John McCall409fa9a2010-12-06 20:48:59 +0000373 // C++ [conv.lval]p1:
374 // [...] If T is a non-class type, the type of the prvalue is the
375 // cv-unqualified version of T. Otherwise, the type of the
376 // rvalue is T.
377 //
378 // C99 6.3.2.1p2:
379 // If the lvalue has qualified type, the value has the unqualified
380 // version of the type of the lvalue; otherwise, the value has the
381 // type of the lvalue.
382 if (T.hasQualifiers())
383 T = T.getUnqualifiedType();
Ted Kremeneka0125d82011-02-16 01:57:07 +0000384
John Wiegley429bb272011-04-08 18:41:53 +0000385 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
386 E, 0, VK_RValue));
John McCall409fa9a2010-12-06 20:48:59 +0000387}
388
John Wiegley429bb272011-04-08 18:41:53 +0000389ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
390 ExprResult Res = DefaultFunctionArrayConversion(E);
391 if (Res.isInvalid())
392 return ExprError();
393 Res = DefaultLvalueConversion(Res.take());
394 if (Res.isInvalid())
395 return ExprError();
396 return move(Res);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000397}
398
399
Chris Lattnere7a2e912008-07-25 21:10:04 +0000400/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000401/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000402/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000403/// apply if the array is an argument to the sizeof or address (&) operators.
404/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000405ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000406 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000407 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
408 if (Res.isInvalid())
409 return Owned(E);
410 E = Res.take();
John McCall0ae287a2010-12-01 04:43:34 +0000411
412 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000413 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCall0ae287a2010-12-01 04:43:34 +0000414
415 // Try to perform integral promotions if the object has a theoretically
416 // promotable type.
417 if (Ty->isIntegralOrUnscopedEnumerationType()) {
418 // C99 6.3.1.1p2:
419 //
420 // The following may be used in an expression wherever an int or
421 // unsigned int may be used:
422 // - an object or expression with an integer type whose integer
423 // conversion rank is less than or equal to the rank of int
424 // and unsigned int.
425 // - A bit-field of type _Bool, int, signed int, or unsigned int.
426 //
427 // If an int can represent all values of the original type, the
428 // value is converted to an int; otherwise, it is converted to an
429 // unsigned int. These are called the integer promotions. All
430 // other types are unchanged by the integer promotions.
431
432 QualType PTy = Context.isPromotableBitField(E);
433 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000434 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
435 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000436 }
437 if (Ty->isPromotableIntegerType()) {
438 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000439 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
440 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000441 }
Eli Friedman04e83572009-08-20 04:21:42 +0000442 }
John Wiegley429bb272011-04-08 18:41:53 +0000443 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000444}
445
Chris Lattner05faf172008-07-25 22:25:12 +0000446/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000447/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000448/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000449ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
450 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000451 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000452
John Wiegley429bb272011-04-08 18:41:53 +0000453 ExprResult Res = UsualUnaryConversions(E);
454 if (Res.isInvalid())
455 return Owned(E);
456 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000457
Chris Lattner05faf172008-07-25 22:25:12 +0000458 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000459 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000460 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
461
John McCall96a914a2011-08-27 22:06:17 +0000462 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-08-29 23:55:37 +0000463 // promotion, even on class types, but note:
464 // C++11 [conv.lval]p2:
465 // When an lvalue-to-rvalue conversion occurs in an unevaluated
466 // operand or a subexpression thereof the value contained in the
467 // referenced object is not accessed. Otherwise, if the glvalue
468 // has a class type, the conversion copy-initializes a temporary
469 // of type T from the glvalue and the result of the conversion
470 // is a prvalue for the temporary.
471 // FIXME: add some way to gate this entire thing for correctness in
472 // potentially potentially evaluated contexts.
John McCall96a914a2011-08-27 22:06:17 +0000473 if (getLangOptions().CPlusPlus && E->isGLValue() &&
474 ExprEvalContexts.back().Context != Unevaluated) {
John McCall5f8d6042011-08-27 01:09:30 +0000475 ExprResult Temp = PerformCopyInitialization(
476 InitializedEntity::InitializeTemporary(E->getType()),
477 E->getExprLoc(),
478 Owned(E));
479 if (Temp.isInvalid())
480 return ExprError();
481 E = Temp.get();
482 }
483
John Wiegley429bb272011-04-08 18:41:53 +0000484 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000485}
486
Chris Lattner312531a2009-04-12 08:11:20 +0000487/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
488/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley429bb272011-04-08 18:41:53 +0000489/// interfaces passed by value.
490ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000491 FunctionDecl *FDecl) {
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000492 ExprResult ExprRes = CheckPlaceholderExpr(E);
493 if (ExprRes.isInvalid())
494 return ExprError();
495
496 ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000497 if (ExprRes.isInvalid())
498 return ExprError();
499 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000501 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley429bb272011-04-08 18:41:53 +0000502 if (E->getType()->isObjCObjectType() &&
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000503 DiagRuntimeBehavior(E->getLocStart(), 0,
504 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
505 << E->getType() << CT))
John Wiegley429bb272011-04-08 18:41:53 +0000506 return ExprError();
John McCall5f8d6042011-08-27 01:09:30 +0000507
John McCallf85e1932011-06-15 23:02:42 +0000508 if (!E->getType().isPODType(Context)) {
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000509 // C++0x [expr.call]p7:
510 // Passing a potentially-evaluated argument of class type (Clause 9)
511 // having a non-trivial copy constructor, a non-trivial move constructor,
512 // or a non-trivial destructor, with no corresponding parameter,
513 // is conditionally-supported with implementation-defined semantics.
514 bool TrivialEnough = false;
515 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
516 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
517 if (Record->hasTrivialCopyConstructor() &&
518 Record->hasTrivialMoveConstructor() &&
519 Record->hasTrivialDestructor())
520 TrivialEnough = true;
521 }
522 }
John McCallf85e1932011-06-15 23:02:42 +0000523
524 if (!TrivialEnough &&
525 getLangOptions().ObjCAutoRefCount &&
526 E->getType()->isObjCLifetimeType())
527 TrivialEnough = true;
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000528
529 if (TrivialEnough) {
530 // Nothing to diagnose. This is okay.
531 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000532 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000533 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000534 << CT)) {
535 // Turn this into a trap.
536 CXXScopeSpec SS;
537 UnqualifiedId Name;
538 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
539 E->getLocStart());
540 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
541 if (TrapFn.isInvalid())
542 return ExprError();
543
544 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
545 MultiExprArg(), E->getLocEnd());
546 if (Call.isInvalid())
547 return ExprError();
548
549 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
550 Call.get(), E);
551 if (Comma.isInvalid())
John McCall66c20302011-08-26 18:41:18 +0000552 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000553 E = Comma.get();
554 }
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000555 }
556
John Wiegley429bb272011-04-08 18:41:53 +0000557 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000558}
559
Richard Trieu8289f492011-09-02 20:58:51 +0000560/// \brief Converts an integer to complex float type. Helper function of
561/// UsualArithmeticConversions()
562///
563/// \return false if the integer expression is an integer type and is
564/// successfully converted to the complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000565static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
566 ExprResult &ComplexExpr,
567 QualType IntTy,
568 QualType ComplexTy,
569 bool SkipCast) {
570 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
571 if (SkipCast) return false;
572 if (IntTy->isIntegerType()) {
573 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
574 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
575 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000576 CK_FloatingRealToComplex);
577 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +0000578 assert(IntTy->isComplexIntegerType());
579 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000580 CK_IntegralComplexToFloatingComplex);
581 }
582 return false;
583}
584
585/// \brief Takes two complex float types and converts them to the same type.
586/// Helper function of UsualArithmeticConversions()
587static QualType
Richard Trieucafd30b2011-09-06 18:25:09 +0000588handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
589 ExprResult &RHS, QualType LHSType,
590 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000591 bool IsCompAssign) {
Richard Trieucafd30b2011-09-06 18:25:09 +0000592 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000593
594 if (order < 0) {
595 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000596 if (!IsCompAssign)
Richard Trieucafd30b2011-09-06 18:25:09 +0000597 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
598 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000599 }
600 if (order > 0)
601 // _Complex float -> _Complex double
Richard Trieucafd30b2011-09-06 18:25:09 +0000602 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
603 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000604}
605
606/// \brief Converts otherExpr to complex float and promotes complexExpr if
607/// necessary. Helper function of UsualArithmeticConversions()
608static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuccd891a2011-09-09 01:45:06 +0000609 ExprResult &ComplexExpr,
610 ExprResult &OtherExpr,
611 QualType ComplexTy,
612 QualType OtherTy,
613 bool ConvertComplexExpr,
614 bool ConvertOtherExpr) {
615 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000616
617 // If just the complexExpr is complex, the otherExpr needs to be converted,
618 // and the complexExpr might need to be promoted.
619 if (order > 0) { // complexExpr is wider
620 // float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000621 if (ConvertOtherExpr) {
622 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
623 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
624 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000625 CK_FloatingRealToComplex);
626 }
Richard Trieuccd891a2011-09-09 01:45:06 +0000627 return ComplexTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000628 }
629
630 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000631 QualType result = (order == 0 ? ComplexTy :
632 S.Context.getComplexType(OtherTy));
Richard Trieu8289f492011-09-02 20:58:51 +0000633
634 // double -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000635 if (ConvertOtherExpr)
636 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000637 CK_FloatingRealToComplex);
638
639 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000640 if (ConvertComplexExpr && order < 0)
641 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000642 CK_FloatingComplexCast);
643
644 return result;
645}
646
647/// \brief Handle arithmetic conversion with complex types. Helper function of
648/// UsualArithmeticConversions()
Richard Trieucafd30b2011-09-06 18:25:09 +0000649static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
650 ExprResult &RHS, QualType LHSType,
651 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000652 bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000653 // if we have an integer operand, the result is the complex type.
Richard Trieucafd30b2011-09-06 18:25:09 +0000654 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000655 /*skipCast*/false))
Richard Trieucafd30b2011-09-06 18:25:09 +0000656 return LHSType;
657 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000658 /*skipCast*/IsCompAssign))
Richard Trieucafd30b2011-09-06 18:25:09 +0000659 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000660
661 // This handles complex/complex, complex/float, or float/complex.
662 // When both operands are complex, the shorter operand is converted to the
663 // type of the longer, and that is the type of the result. This corresponds
664 // to what is done when combining two real floating-point operands.
665 // The fun begins when size promotion occur across type domains.
666 // From H&S 6.3.4: When one operand is complex and the other is a real
667 // floating-point type, the less precise type is converted, within it's
668 // real or complex domain, to the precision of the other type. For example,
669 // when combining a "long double" with a "double _Complex", the
670 // "double _Complex" is promoted to "long double _Complex".
671
Richard Trieucafd30b2011-09-06 18:25:09 +0000672 bool LHSComplexFloat = LHSType->isComplexType();
673 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu8289f492011-09-02 20:58:51 +0000674
675 // If both are complex, just cast to the more precise type.
676 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieucafd30b2011-09-06 18:25:09 +0000677 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
678 LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000679 IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000680
681 // If only one operand is complex, promote it if necessary and convert the
682 // other operand to complex.
683 if (LHSComplexFloat)
684 return handleOtherComplexFloatConversion(
Richard Trieuccd891a2011-09-09 01:45:06 +0000685 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000686 /*convertOtherExpr*/ true);
687
688 assert(RHSComplexFloat);
689 return handleOtherComplexFloatConversion(
Richard Trieucafd30b2011-09-06 18:25:09 +0000690 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000691 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000692}
693
694/// \brief Hande arithmetic conversion from integer to float. Helper function
695/// of UsualArithmeticConversions()
Richard Trieuccd891a2011-09-09 01:45:06 +0000696static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
697 ExprResult &IntExpr,
698 QualType FloatTy, QualType IntTy,
699 bool ConvertFloat, bool ConvertInt) {
700 if (IntTy->isIntegerType()) {
701 if (ConvertInt)
Richard Trieu8289f492011-09-02 20:58:51 +0000702 // Convert intExpr to the lhs floating point type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000703 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000704 CK_IntegralToFloating);
Richard Trieuccd891a2011-09-09 01:45:06 +0000705 return FloatTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000706 }
707
708 // Convert both sides to the appropriate complex float.
Richard Trieuccd891a2011-09-09 01:45:06 +0000709 assert(IntTy->isComplexIntegerType());
710 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000711
712 // _Complex int -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000713 if (ConvertInt)
714 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000715 CK_IntegralComplexToFloatingComplex);
716
717 // float -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000718 if (ConvertFloat)
719 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000720 CK_FloatingRealToComplex);
721
722 return result;
723}
724
725/// \brief Handle arithmethic conversion with floating point types. Helper
726/// function of UsualArithmeticConversions()
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000727static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
728 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000729 QualType RHSType, bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000730 bool LHSFloat = LHSType->isRealFloatingType();
731 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu8289f492011-09-02 20:58:51 +0000732
733 // If we have two real floating types, convert the smaller operand
734 // to the bigger result.
735 if (LHSFloat && RHSFloat) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000736 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000737 if (order > 0) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000738 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
739 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000740 }
741
742 assert(order < 0 && "illegal float comparison");
Richard Trieuccd891a2011-09-09 01:45:06 +0000743 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000744 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
745 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000746 }
747
748 if (LHSFloat)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000749 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000750 /*convertFloat=*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000751 /*convertInt=*/ true);
752 assert(RHSFloat);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000753 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000754 /*convertInt=*/ true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000755 /*convertFloat=*/!IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000756}
757
758/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000759/// of UsualArithmeticConversions()
Richard Trieu8289f492011-09-02 20:58:51 +0000760// FIXME: if the operands are (int, _Complex long), we currently
761// don't promote the complex. Also, signedness?
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000762static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
763 ExprResult &RHS, QualType LHSType,
764 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000765 bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000766 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
767 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu8289f492011-09-02 20:58:51 +0000768
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000769 if (LHSComplexInt && RHSComplexInt) {
770 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
771 RHSComplexInt->getElementType());
Richard Trieu8289f492011-09-02 20:58:51 +0000772 assert(order && "inequal types with equal element ordering");
773 if (order > 0) {
774 // _Complex int -> _Complex long
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000775 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
776 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000777 }
778
Richard Trieuccd891a2011-09-09 01:45:06 +0000779 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000780 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
781 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000782 }
783
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000784 if (LHSComplexInt) {
Richard Trieu8289f492011-09-02 20:58:51 +0000785 // int -> _Complex int
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000786 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
787 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000788 }
789
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000790 assert(RHSComplexInt);
Richard Trieu8289f492011-09-02 20:58:51 +0000791 // int -> _Complex int
Richard Trieuccd891a2011-09-09 01:45:06 +0000792 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000793 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
794 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000795}
796
797/// \brief Handle integer arithmetic conversions. Helper function of
798/// UsualArithmeticConversions()
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000799static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
800 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000801 QualType RHSType, bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000802 // The rules for this case are in C99 6.3.1.8
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000803 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
804 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
805 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
806 if (LHSSigned == RHSSigned) {
Richard Trieu8289f492011-09-02 20:58:51 +0000807 // Same signedness; use the higher-ranked type
808 if (order >= 0) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000809 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
810 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000811 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000812 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
813 return RHSType;
814 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000815 // The unsigned type has greater than or equal rank to the
816 // signed type, so use the unsigned type
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000817 if (RHSSigned) {
818 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
819 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000820 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000821 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
822 return RHSType;
823 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000824 // The two types are different widths; if we are here, that
825 // means the signed type is larger than the unsigned type, so
826 // use the signed type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000827 if (LHSSigned) {
828 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
829 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000830 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000831 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
832 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000833 } else {
834 // The signed type is higher-ranked than the unsigned type,
835 // but isn't actually any bigger (like unsigned int and long
836 // on most 32-bit systems). Use the unsigned type corresponding
837 // to the signed type.
838 QualType result =
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000839 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
840 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuccd891a2011-09-09 01:45:06 +0000841 if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000842 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu8289f492011-09-02 20:58:51 +0000843 return result;
844 }
845}
846
Chris Lattnere7a2e912008-07-25 21:10:04 +0000847/// UsualArithmeticConversions - Performs various conversions that are common to
848/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000849/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000850/// responsible for emitting appropriate error diagnostics.
851/// FIXME: verify the conversion rules for "complex int" are consistent with
852/// GCC.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000853QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +0000854 bool IsCompAssign) {
855 if (!IsCompAssign) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000856 LHS = UsualUnaryConversions(LHS.take());
857 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000858 return QualType();
859 }
Eli Friedmanab3a8522009-03-28 01:22:36 +0000860
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000861 RHS = UsualUnaryConversions(RHS.take());
862 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000863 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000864
Mike Stump1eb44332009-09-09 15:08:12 +0000865 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000866 // For example, "const float" and "float" are equivalent.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000867 QualType LHSType =
868 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
869 QualType RHSType =
870 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000871
872 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000873 if (LHSType == RHSType)
874 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000875
876 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
877 // The caller can deal with this (e.g. pointer + int).
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000878 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
879 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000880
John McCallcf33b242010-11-13 08:17:45 +0000881 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000882 QualType LHSUnpromotedType = LHSType;
883 if (LHSType->isPromotableIntegerType())
884 LHSType = Context.getPromotedIntegerType(LHSType);
885 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +0000886 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000887 LHSType = LHSBitfieldPromoteTy;
Richard Trieuccd891a2011-09-09 01:45:06 +0000888 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000889 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000890
John McCallcf33b242010-11-13 08:17:45 +0000891 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000892 if (LHSType == RHSType)
893 return LHSType;
John McCallcf33b242010-11-13 08:17:45 +0000894
895 // At this point, we have two different arithmetic types.
896
897 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000898 if (LHSType->isComplexType() || RHSType->isComplexType())
899 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000900 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000901
902 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000903 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
904 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000905 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000906
907 // Handle GCC complex int extension.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000908 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000909 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000910 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000911
912 // Finally, we have two differing integer types.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000913 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000914 IsCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000915}
916
Chris Lattnere7a2e912008-07-25 21:10:04 +0000917//===----------------------------------------------------------------------===//
918// Semantic Analysis for various Expression Types
919//===----------------------------------------------------------------------===//
920
921
Peter Collingbournef111d932011-04-15 00:35:48 +0000922ExprResult
923Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
924 SourceLocation DefaultLoc,
925 SourceLocation RParenLoc,
926 Expr *ControllingExpr,
Richard Trieuccd891a2011-09-09 01:45:06 +0000927 MultiTypeArg ArgTypes,
928 MultiExprArg ArgExprs) {
929 unsigned NumAssocs = ArgTypes.size();
930 assert(NumAssocs == ArgExprs.size());
Peter Collingbournef111d932011-04-15 00:35:48 +0000931
Richard Trieuccd891a2011-09-09 01:45:06 +0000932 ParsedType *ParsedTypes = ArgTypes.release();
933 Expr **Exprs = ArgExprs.release();
Peter Collingbournef111d932011-04-15 00:35:48 +0000934
935 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
936 for (unsigned i = 0; i < NumAssocs; ++i) {
937 if (ParsedTypes[i])
938 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
939 else
940 Types[i] = 0;
941 }
942
943 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
944 ControllingExpr, Types, Exprs,
945 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +0000946 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +0000947 return ER;
948}
949
950ExprResult
951Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
952 SourceLocation DefaultLoc,
953 SourceLocation RParenLoc,
954 Expr *ControllingExpr,
955 TypeSourceInfo **Types,
956 Expr **Exprs,
957 unsigned NumAssocs) {
958 bool TypeErrorFound = false,
959 IsResultDependent = ControllingExpr->isTypeDependent(),
960 ContainsUnexpandedParameterPack
961 = ControllingExpr->containsUnexpandedParameterPack();
962
963 for (unsigned i = 0; i < NumAssocs; ++i) {
964 if (Exprs[i]->containsUnexpandedParameterPack())
965 ContainsUnexpandedParameterPack = true;
966
967 if (Types[i]) {
968 if (Types[i]->getType()->containsUnexpandedParameterPack())
969 ContainsUnexpandedParameterPack = true;
970
971 if (Types[i]->getType()->isDependentType()) {
972 IsResultDependent = true;
973 } else {
974 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
975 // complete object type other than a variably modified type."
976 unsigned D = 0;
977 if (Types[i]->getType()->isIncompleteType())
978 D = diag::err_assoc_type_incomplete;
979 else if (!Types[i]->getType()->isObjectType())
980 D = diag::err_assoc_type_nonobject;
981 else if (Types[i]->getType()->isVariablyModifiedType())
982 D = diag::err_assoc_type_variably_modified;
983
984 if (D != 0) {
985 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
986 << Types[i]->getTypeLoc().getSourceRange()
987 << Types[i]->getType();
988 TypeErrorFound = true;
989 }
990
991 // C1X 6.5.1.1p2 "No two generic associations in the same generic
992 // selection shall specify compatible types."
993 for (unsigned j = i+1; j < NumAssocs; ++j)
994 if (Types[j] && !Types[j]->getType()->isDependentType() &&
995 Context.typesAreCompatible(Types[i]->getType(),
996 Types[j]->getType())) {
997 Diag(Types[j]->getTypeLoc().getBeginLoc(),
998 diag::err_assoc_compatible_types)
999 << Types[j]->getTypeLoc().getSourceRange()
1000 << Types[j]->getType()
1001 << Types[i]->getType();
1002 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1003 diag::note_compat_assoc)
1004 << Types[i]->getTypeLoc().getSourceRange()
1005 << Types[i]->getType();
1006 TypeErrorFound = true;
1007 }
1008 }
1009 }
1010 }
1011 if (TypeErrorFound)
1012 return ExprError();
1013
1014 // If we determined that the generic selection is result-dependent, don't
1015 // try to compute the result expression.
1016 if (IsResultDependent)
1017 return Owned(new (Context) GenericSelectionExpr(
1018 Context, KeyLoc, ControllingExpr,
1019 Types, Exprs, NumAssocs, DefaultLoc,
1020 RParenLoc, ContainsUnexpandedParameterPack));
1021
Chris Lattner5f9e2722011-07-23 10:55:15 +00001022 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +00001023 unsigned DefaultIndex = -1U;
1024 for (unsigned i = 0; i < NumAssocs; ++i) {
1025 if (!Types[i])
1026 DefaultIndex = i;
1027 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1028 Types[i]->getType()))
1029 CompatIndices.push_back(i);
1030 }
1031
1032 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
1033 // type compatible with at most one of the types named in its generic
1034 // association list."
1035 if (CompatIndices.size() > 1) {
1036 // We strip parens here because the controlling expression is typically
1037 // parenthesized in macro definitions.
1038 ControllingExpr = ControllingExpr->IgnoreParens();
1039 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1040 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1041 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001042 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001043 E = CompatIndices.end(); I != E; ++I) {
1044 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1045 diag::note_compat_assoc)
1046 << Types[*I]->getTypeLoc().getSourceRange()
1047 << Types[*I]->getType();
1048 }
1049 return ExprError();
1050 }
1051
1052 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
1053 // its controlling expression shall have type compatible with exactly one of
1054 // the types named in its generic association list."
1055 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1056 // We strip parens here because the controlling expression is typically
1057 // parenthesized in macro definitions.
1058 ControllingExpr = ControllingExpr->IgnoreParens();
1059 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1060 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1061 return ExprError();
1062 }
1063
1064 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1065 // type name that is compatible with the type of the controlling expression,
1066 // then the result expression of the generic selection is the expression
1067 // in that generic association. Otherwise, the result expression of the
1068 // generic selection is the expression in the default generic association."
1069 unsigned ResultIndex =
1070 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1071
1072 return Owned(new (Context) GenericSelectionExpr(
1073 Context, KeyLoc, ControllingExpr,
1074 Types, Exprs, NumAssocs, DefaultLoc,
1075 RParenLoc, ContainsUnexpandedParameterPack,
1076 ResultIndex));
1077}
1078
Steve Narofff69936d2007-09-16 03:34:24 +00001079/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001080/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1081/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1082/// multiple tokens. However, the common case is that StringToks points to one
1083/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001084///
John McCall60d7b3a2010-08-24 06:29:42 +00001085ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +00001086Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001087 assert(NumStringToks && "Must have at least one string!");
1088
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001089 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001090 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001091 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001092
Chris Lattner5f9e2722011-07-23 10:55:15 +00001093 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001094 for (unsigned i = 0; i != NumStringToks; ++i)
1095 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001096
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001097 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001098 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001099 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001100 else if (Literal.isUTF16())
1101 StrTy = Context.Char16Ty;
1102 else if (Literal.isUTF32())
1103 StrTy = Context.Char32Ty;
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001104 else if (Literal.Pascal)
1105 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001106
Douglas Gregor5cee1192011-07-27 05:40:30 +00001107 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1108 if (Literal.isWide())
1109 Kind = StringLiteral::Wide;
1110 else if (Literal.isUTF8())
1111 Kind = StringLiteral::UTF8;
1112 else if (Literal.isUTF16())
1113 Kind = StringLiteral::UTF16;
1114 else if (Literal.isUTF32())
1115 Kind = StringLiteral::UTF32;
1116
Douglas Gregor77a52232008-09-12 00:47:35 +00001117 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +00001118 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001119 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001120
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001121 // Get an array type for the string, according to C99 6.4.5. This includes
1122 // the nul terminator character as well as the string length for pascal
1123 // strings.
1124 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001125 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001126 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Reid Spencer5f016e22007-07-11 17:01:13 +00001128 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +00001129 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001130 Kind, Literal.Pascal, StrTy,
Sean Hunt6cf75022010-08-30 17:47:05 +00001131 &StringTokLocs[0],
1132 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001133}
1134
John McCall469a1eb2011-02-02 13:00:07 +00001135enum CaptureResult {
1136 /// No capture is required.
1137 CR_NoCapture,
1138
1139 /// A capture is required.
1140 CR_Capture,
1141
John McCall6b5a61b2011-02-07 10:33:21 +00001142 /// A by-ref capture is required.
1143 CR_CaptureByRef,
1144
John McCall469a1eb2011-02-02 13:00:07 +00001145 /// An error occurred when trying to capture the given variable.
1146 CR_Error
1147};
1148
1149/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +00001150///
John McCall469a1eb2011-02-02 13:00:07 +00001151/// \param var - the variable referenced
1152/// \param DC - the context which we couldn't capture through
1153static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +00001154diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001155 VarDecl *var, DeclContext *DC) {
1156 switch (S.ExprEvalContexts.back().Context) {
1157 case Sema::Unevaluated:
1158 // The argument will never be evaluated, so don't complain.
1159 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +00001160
John McCall469a1eb2011-02-02 13:00:07 +00001161 case Sema::PotentiallyEvaluated:
1162 case Sema::PotentiallyEvaluatedIfUsed:
1163 break;
Chris Lattner639e2d32008-10-20 05:16:36 +00001164
John McCall469a1eb2011-02-02 13:00:07 +00001165 case Sema::PotentiallyPotentiallyEvaluated:
1166 // FIXME: delay these!
1167 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +00001168 }
Mike Stump1eb44332009-09-09 15:08:12 +00001169
John McCall469a1eb2011-02-02 13:00:07 +00001170 // Don't diagnose about capture if we're not actually in code right
1171 // now; in general, there are more appropriate places that will
1172 // diagnose this.
1173 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1174
John McCall4f38f412011-03-22 23:15:50 +00001175 // Certain madnesses can happen with parameter declarations, which
1176 // we want to ignore.
1177 if (isa<ParmVarDecl>(var)) {
1178 // - If the parameter still belongs to the translation unit, then
1179 // we're actually just using one parameter in the declaration of
1180 // the next. This is useful in e.g. VLAs.
1181 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1182 return CR_NoCapture;
1183
1184 // - This particular madness can happen in ill-formed default
1185 // arguments; claim it's okay and let downstream code handle it.
1186 if (S.CurContext == var->getDeclContext()->getParent())
1187 return CR_NoCapture;
1188 }
John McCall469a1eb2011-02-02 13:00:07 +00001189
1190 DeclarationName functionName;
1191 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1192 functionName = fn->getDeclName();
1193 // FIXME: variable from enclosing block that we couldn't capture from!
1194
1195 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1196 << var->getIdentifier() << functionName;
1197 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1198 << var->getIdentifier();
1199
1200 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001201}
1202
John McCall6b5a61b2011-02-07 10:33:21 +00001203/// There is a well-formed capture at a particular scope level;
1204/// propagate it through all the nested blocks.
Richard Trieuccd891a2011-09-09 01:45:06 +00001205static CaptureResult propagateCapture(Sema &S, unsigned ValidScopeIndex,
1206 const BlockDecl::Capture &Capture) {
1207 VarDecl *var = Capture.getVariable();
John McCall6b5a61b2011-02-07 10:33:21 +00001208
1209 // Update all the inner blocks with the capture information.
Richard Trieuccd891a2011-09-09 01:45:06 +00001210 for (unsigned i = ValidScopeIndex + 1, e = S.FunctionScopes.size();
John McCall6b5a61b2011-02-07 10:33:21 +00001211 i != e; ++i) {
1212 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1213 innerBlock->Captures.push_back(
Richard Trieuccd891a2011-09-09 01:45:06 +00001214 BlockDecl::Capture(Capture.getVariable(), Capture.isByRef(),
1215 /*nested*/ true, Capture.getCopyExpr()));
John McCall6b5a61b2011-02-07 10:33:21 +00001216 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1217 }
1218
Richard Trieuccd891a2011-09-09 01:45:06 +00001219 return Capture.isByRef() ? CR_CaptureByRef : CR_Capture;
John McCall6b5a61b2011-02-07 10:33:21 +00001220}
1221
1222/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +00001223/// given value in the current context requires a variable capture.
1224///
1225/// This also keeps the captures set in the BlockScopeInfo records
1226/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +00001227static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00001228 ValueDecl *Value) {
John McCall469a1eb2011-02-02 13:00:07 +00001229 // Only variables ever require capture.
Richard Trieuccd891a2011-09-09 01:45:06 +00001230 VarDecl *var = dyn_cast<VarDecl>(Value);
John McCall76a40212011-02-09 01:13:10 +00001231 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +00001232
1233 // Fast path: variables from the current context never require capture.
1234 DeclContext *DC = S.CurContext;
1235 if (var->getDeclContext() == DC) return CR_NoCapture;
1236
1237 // Only variables with local storage require capture.
1238 // FIXME: What about 'const' variables in C++?
1239 if (!var->hasLocalStorage()) return CR_NoCapture;
1240
1241 // Otherwise, we need to capture.
1242
1243 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +00001244 do {
1245 // Only blocks (and eventually C++0x closures) can capture; other
1246 // scopes don't work.
1247 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +00001248 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +00001249
1250 BlockScopeInfo *blockScope =
1251 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1252 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1253
John McCall6b5a61b2011-02-07 10:33:21 +00001254 // Check whether we've already captured it in this block. If so,
1255 // we're done.
1256 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1257 return propagateCapture(S, functionScopesIndex,
1258 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +00001259
1260 functionScopesIndex--;
1261 DC = cast<BlockDecl>(DC)->getDeclContext();
1262 } while (var->getDeclContext() != DC);
1263
John McCall6b5a61b2011-02-07 10:33:21 +00001264 // Okay, we descended all the way to the block that defines the variable.
1265 // Actually try to capture it.
1266 QualType type = var->getType();
1267
1268 // Prohibit variably-modified types.
1269 if (type->isVariablyModifiedType()) {
1270 S.Diag(loc, diag::err_ref_vm_type);
1271 S.Diag(var->getLocation(), diag::note_declared_at);
1272 return CR_Error;
1273 }
1274
1275 // Prohibit arrays, even in __block variables, but not references to
1276 // them.
1277 if (type->isArrayType()) {
1278 S.Diag(loc, diag::err_ref_array_type);
1279 S.Diag(var->getLocation(), diag::note_declared_at);
1280 return CR_Error;
1281 }
1282
1283 S.MarkDeclarationReferenced(loc, var);
1284
1285 // The BlocksAttr indicates the variable is bound by-reference.
1286 bool byRef = var->hasAttr<BlocksAttr>();
1287
1288 // Build a copy expression.
1289 Expr *copyExpr = 0;
John McCall642a75f2011-04-28 02:15:35 +00001290 const RecordType *rtype;
1291 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1292 (rtype = type->getAs<RecordType>())) {
1293
1294 // The capture logic needs the destructor, so make sure we mark it.
1295 // Usually this is unnecessary because most local variables have
1296 // their destructors marked at declaration time, but parameters are
1297 // an exception because it's technically only the call site that
1298 // actually requires the destructor.
1299 if (isa<ParmVarDecl>(var))
1300 S.FinalizeVarWithDestructor(var, rtype);
1301
John McCall6b5a61b2011-02-07 10:33:21 +00001302 // According to the blocks spec, the capture of a variable from
1303 // the stack requires a const copy constructor. This is not true
1304 // of the copy/move done to move a __block variable to the heap.
1305 type.addConst();
1306
1307 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1308 ExprResult result =
1309 S.PerformCopyInitialization(
1310 InitializedEntity::InitializeBlock(var->getLocation(),
1311 type, false),
1312 loc, S.Owned(declRef));
1313
1314 // Build a full-expression copy expression if initialization
1315 // succeeded and used a non-trivial constructor. Recover from
1316 // errors by pretending that the copy isn't necessary.
1317 if (!result.isInvalid() &&
1318 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1319 result = S.MaybeCreateExprWithCleanups(result);
1320 copyExpr = result.take();
1321 }
1322 }
1323
1324 // We're currently at the declarer; go back to the closure.
1325 functionScopesIndex++;
1326 BlockScopeInfo *blockScope =
1327 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1328
1329 // Build a valid capture in this scope.
1330 blockScope->Captures.push_back(
1331 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1332 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1333
1334 // Propagate that to inner captures if necessary.
1335 return propagateCapture(S, functionScopesIndex,
1336 blockScope->Captures.back());
1337}
1338
Richard Trieuccd891a2011-09-09 01:45:06 +00001339static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD,
John McCall6b5a61b2011-02-07 10:33:21 +00001340 const DeclarationNameInfo &NameInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00001341 bool ByRef) {
1342 assert(isa<VarDecl>(VD) && "capturing non-variable");
John McCall6b5a61b2011-02-07 10:33:21 +00001343
Richard Trieuccd891a2011-09-09 01:45:06 +00001344 VarDecl *var = cast<VarDecl>(VD);
John McCall6b5a61b2011-02-07 10:33:21 +00001345 assert(var->hasLocalStorage() && "capturing non-local");
Richard Trieuccd891a2011-09-09 01:45:06 +00001346 assert(ByRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
John McCall6b5a61b2011-02-07 10:33:21 +00001347
1348 QualType exprType = var->getType().getNonReferenceType();
1349
1350 BlockDeclRefExpr *BDRE;
Richard Trieuccd891a2011-09-09 01:45:06 +00001351 if (!ByRef) {
John McCall6b5a61b2011-02-07 10:33:21 +00001352 // The variable will be bound by copy; make it const within the
1353 // closure, but record that this was done in the expression.
1354 bool constAdded = !exprType.isConstQualified();
1355 exprType.addConst();
1356
1357 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1358 NameInfo.getLoc(), false,
1359 constAdded);
1360 } else {
1361 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1362 NameInfo.getLoc(), true);
1363 }
1364
1365 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +00001366}
Chris Lattner639e2d32008-10-20 05:16:36 +00001367
John McCall60d7b3a2010-08-24 06:29:42 +00001368ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001369Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001370 SourceLocation Loc,
1371 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001372 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001373 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001374}
1375
John McCall76a40212011-02-09 01:13:10 +00001376/// BuildDeclRefExpr - Build an expression that references a
1377/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001378ExprResult
John McCall76a40212011-02-09 01:13:10 +00001379Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001380 const DeclarationNameInfo &NameInfo,
1381 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001382 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +00001383
John McCall7eb0a9e2010-11-24 05:12:34 +00001384 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00001385 SS? SS->getWithLocInContext(Context)
1386 : NestedNameSpecifierLoc(),
John McCall7eb0a9e2010-11-24 05:12:34 +00001387 D, NameInfo, Ty, VK);
1388
1389 // Just in case we're building an illegal pointer-to-member.
1390 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1391 E->setObjectKind(OK_BitField);
1392
1393 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001394}
1395
Abramo Bagnara25777432010-08-11 22:01:17 +00001396/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001397/// possibly a list of template arguments.
1398///
1399/// If this produces template arguments, it is permitted to call
1400/// DecomposeTemplateName.
1401///
1402/// This actually loses a lot of source location information for
1403/// non-standard name kinds; we should consider preserving that in
1404/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001405void
1406Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1407 TemplateArgumentListInfo &Buffer,
1408 DeclarationNameInfo &NameInfo,
1409 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001410 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1411 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1412 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1413
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001414 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall129e2df2009-11-30 22:42:35 +00001415 Id.TemplateId->getTemplateArgs(),
1416 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001417 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001418 TemplateArgsPtr.release();
1419
John McCall2b5289b2010-08-23 07:28:44 +00001420 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001421 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001422 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001423 TemplateArgs = &Buffer;
1424 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001425 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001426 TemplateArgs = 0;
1427 }
1428}
1429
John McCall578b69b2009-12-16 08:11:27 +00001430/// Diagnose an empty lookup.
1431///
1432/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001433bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001434 CorrectTypoContext CTC,
1435 TemplateArgumentListInfo *ExplicitTemplateArgs,
1436 Expr **Args, unsigned NumArgs) {
John McCall578b69b2009-12-16 08:11:27 +00001437 DeclarationName Name = R.getLookupName();
1438
John McCall578b69b2009-12-16 08:11:27 +00001439 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001440 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001441 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1442 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001443 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001444 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001445 diagnostic_suggest = diag::err_undeclared_use_suggest;
1446 }
John McCall578b69b2009-12-16 08:11:27 +00001447
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001448 // If the original lookup was an unqualified lookup, fake an
1449 // unqualified lookup. This is useful when (for example) the
1450 // original lookup would not have found something because it was a
1451 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001452 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001453 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001454 if (isa<CXXRecordDecl>(DC)) {
1455 LookupQualifiedName(R, DC);
1456
1457 if (!R.empty()) {
1458 // Don't give errors about ambiguities in this lookup.
1459 R.suppressDiagnostics();
1460
1461 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1462 bool isInstance = CurMethod &&
1463 CurMethod->isInstance() &&
1464 DC == CurMethod->getParent();
1465
1466 // Give a code modification hint to insert 'this->'.
1467 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1468 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001469 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001470 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1471 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001472 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001473 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001474 if (DepMethod) {
Francois Pichet62ec1f22011-09-17 17:15:52 +00001475 if (getLangOptions().MicrosoftExt)
Francois Pichet0f74d1e2011-09-07 00:14:57 +00001476 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001477 Diag(R.getNameLoc(), diagnostic) << Name
1478 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1479 QualType DepThisType = DepMethod->getThisType(Context);
1480 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1481 R.getNameLoc(), DepThisType, false);
1482 TemplateArgumentListInfo TList;
1483 if (ULE->hasExplicitTemplateArgs())
1484 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001485
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001486 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00001487 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001488 CXXDependentScopeMemberExpr *DepExpr =
1489 CXXDependentScopeMemberExpr::Create(
1490 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001491 SS.getWithLocInContext(Context), NULL,
Francois Pichetf7400122011-09-04 23:00:48 +00001492 R.getLookupNameInfo(),
1493 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001494 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001495 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001496 // FIXME: we should be able to handle this case too. It is correct
1497 // to add this-> here. This is a workaround for PR7947.
1498 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001499 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001500 } else {
John McCall578b69b2009-12-16 08:11:27 +00001501 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001502 }
John McCall578b69b2009-12-16 08:11:27 +00001503
1504 // Do we really want to note all of these?
1505 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1506 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1507
1508 // Tell the callee to try to recover.
1509 return false;
1510 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001511
1512 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001513 }
1514 }
1515
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001516 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001517 TypoCorrection Corrected;
1518 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1519 S, &SS, NULL, false, CTC))) {
1520 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1521 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1522 R.setLookupName(Corrected.getCorrection());
1523
Hans Wennborg701d1e72011-07-12 08:45:31 +00001524 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001525 if (Corrected.isOverloaded()) {
1526 OverloadCandidateSet OCS(R.getNameLoc());
1527 OverloadCandidateSet::iterator Best;
1528 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1529 CDEnd = Corrected.end();
1530 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001531 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001532 dyn_cast<FunctionTemplateDecl>(*CD))
1533 AddTemplateOverloadCandidate(
1534 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1535 Args, NumArgs, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001536 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1537 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1538 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1539 Args, NumArgs, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001540 }
1541 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1542 case OR_Success:
1543 ND = Best->Function;
1544 break;
1545 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001546 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001547 }
1548 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001549 R.addDecl(ND);
1550 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001551 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001552 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1553 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001554 else
1555 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001556 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001557 << SS.getRange()
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001558 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1559 if (ND)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001560 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001561 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001562
1563 // Tell the callee to try to recover.
1564 return false;
1565 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001566
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001567 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001568 // FIXME: If we ended up with a typo for a type name or
1569 // Objective-C class name, we're in trouble because the parser
1570 // is in the wrong place to recover. Suggest the typo
1571 // correction, but don't make it a fix-it since we're not going
1572 // to recover well anyway.
1573 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001574 Diag(R.getNameLoc(), diagnostic_suggest)
1575 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001576 else
1577 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001578 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001579 << SS.getRange();
1580
1581 // Don't try to recover; it won't work.
1582 return true;
1583 }
1584 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001585 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001586 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001587 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001588 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001589 else
Douglas Gregord203a162010-01-01 00:15:04 +00001590 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001591 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001592 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001593 return true;
1594 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001595 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001596 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001597
1598 // Emit a special diagnostic for failed member lookups.
1599 // FIXME: computing the declaration context might fail here (?)
1600 if (!SS.isEmpty()) {
1601 Diag(R.getNameLoc(), diag::err_no_member)
1602 << Name << computeDeclContext(SS, false)
1603 << SS.getRange();
1604 return true;
1605 }
1606
John McCall578b69b2009-12-16 08:11:27 +00001607 // Give up, we can't recover.
1608 Diag(R.getNameLoc(), diagnostic) << Name;
1609 return true;
1610}
1611
John McCall60d7b3a2010-08-24 06:29:42 +00001612ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001613 CXXScopeSpec &SS,
1614 UnqualifiedId &Id,
1615 bool HasTrailingLParen,
Richard Trieuccd891a2011-09-09 01:45:06 +00001616 bool IsAddressOfOperand) {
1617 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCallf7a1a742009-11-24 19:00:30 +00001618 "cannot be direct & operand and have a trailing lparen");
1619
1620 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001621 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001622
John McCall129e2df2009-11-30 22:42:35 +00001623 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001624
1625 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001626 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001627 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001628 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001629
Abramo Bagnara25777432010-08-11 22:01:17 +00001630 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001631 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001632 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001633
John McCallf7a1a742009-11-24 19:00:30 +00001634 // C++ [temp.dep.expr]p3:
1635 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001636 // -- an identifier that was declared with a dependent type,
1637 // (note: handled after lookup)
1638 // -- a template-id that is dependent,
1639 // (note: handled in BuildTemplateIdExpr)
1640 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001641 // -- a nested-name-specifier that contains a class-name that
1642 // names a dependent type.
1643 // Determine whether this is a member of an unknown specialization;
1644 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001645 bool DependentID = false;
1646 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1647 Name.getCXXNameType()->isDependentType()) {
1648 DependentID = true;
1649 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001650 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001651 if (RequireCompleteDeclContext(SS, DC))
1652 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001653 } else {
1654 DependentID = true;
1655 }
1656 }
1657
Chris Lattner337e5502011-02-18 01:27:55 +00001658 if (DependentID)
Richard Trieuccd891a2011-09-09 01:45:06 +00001659 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001660 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001661
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001662 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001663 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001664 LookupResult R(*this, NameInfo,
1665 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1666 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001667 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001668 // Lookup the template name again to correctly establish the context in
1669 // which it was found. This is really unfortunate as we already did the
1670 // lookup to determine that it was a template name in the first place. If
1671 // this becomes a performance hit, we can work harder to preserve those
1672 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001673 bool MemberOfUnknownSpecialization;
1674 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1675 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001676
1677 if (MemberOfUnknownSpecialization ||
1678 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Richard Trieuccd891a2011-09-09 01:45:06 +00001679 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001680 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001681 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001682 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001683 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001685 // If the result might be in a dependent base class, this is a dependent
1686 // id-expression.
1687 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Richard Trieuccd891a2011-09-09 01:45:06 +00001688 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001689 TemplateArgs);
1690
John McCallf7a1a742009-11-24 19:00:30 +00001691 // If this reference is in an Objective-C method, then we need to do
1692 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001693 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001694 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001695 if (E.isInvalid())
1696 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Chris Lattner337e5502011-02-18 01:27:55 +00001698 if (Expr *Ex = E.takeAs<Expr>())
1699 return Owned(Ex);
1700
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001701 // for further use, this must be set to false if in class method.
1702 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001703 }
Chris Lattner8a934232008-03-31 00:36:02 +00001704 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001705
John McCallf7a1a742009-11-24 19:00:30 +00001706 if (R.isAmbiguous())
1707 return ExprError();
1708
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001709 // Determine whether this name might be a candidate for
1710 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001711 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001712
John McCallf7a1a742009-11-24 19:00:30 +00001713 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001714 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001715 // in C90, extension in C99, forbidden in C++).
1716 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1717 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1718 if (D) R.addDecl(D);
1719 }
1720
1721 // If this name wasn't predeclared and if this is not a function
1722 // call, diagnose the problem.
1723 if (R.empty()) {
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001724
1725 // In Microsoft mode, if we are inside a template class member function
1726 // and we can't resolve an identifier then assume the identifier is type
1727 // dependent. The goal is to postpone name lookup to instantiation time
1728 // to be able to search into type dependent base classes.
1729 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
1730 isa<CXXMethodDecl>(CurContext))
1731 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1732 TemplateArgs);
1733
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001734 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001735 return ExprError();
1736
1737 assert(!R.empty() &&
1738 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001739
1740 // If we found an Objective-C instance variable, let
1741 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001742 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001743 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1744 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001745 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanianbc2b91a2011-09-23 23:11:38 +00001746 // In a hopelessly buggy code, Objective-C instance variable
1747 // lookup fails and no expression will be built to reference it.
1748 if (!E.isInvalid() && !E.get())
1749 return ExprError();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001750 return move(E);
1751 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001752 }
1753 }
Mike Stump1eb44332009-09-09 15:08:12 +00001754
John McCallf7a1a742009-11-24 19:00:30 +00001755 // This is guaranteed from this point on.
1756 assert(!R.empty() || ADL);
1757
John McCallaa81e162009-12-01 22:10:20 +00001758 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001759 // C++ [class.mfct.non-static]p3:
1760 // When an id-expression that is not part of a class member access
1761 // syntax and not used to form a pointer to member is used in the
1762 // body of a non-static member function of class X, if name lookup
1763 // resolves the name in the id-expression to a non-static non-type
1764 // member of some class C, the id-expression is transformed into a
1765 // class member access expression using (*this) as the
1766 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001767 //
1768 // But we don't actually need to do this for '&' operands if R
1769 // resolved to a function or overloaded function set, because the
1770 // expression is ill-formed if it actually works out to be a
1771 // non-static member function:
1772 //
1773 // C++ [expr.ref]p4:
1774 // Otherwise, if E1.E2 refers to a non-static member function. . .
1775 // [t]he expression can be used only as the left-hand operand of a
1776 // member function call.
1777 //
1778 // There are other safeguards against such uses, but it's important
1779 // to get this right here so that we don't end up making a
1780 // spuriously dependent expression if we're inside a dependent
1781 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001782 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001783 bool MightBeImplicitMember;
Richard Trieuccd891a2011-09-09 01:45:06 +00001784 if (!IsAddressOfOperand)
John McCall9c72c602010-08-27 09:08:28 +00001785 MightBeImplicitMember = true;
1786 else if (!SS.isEmpty())
1787 MightBeImplicitMember = false;
1788 else if (R.isOverloadedResult())
1789 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001790 else if (R.isUnresolvableResult())
1791 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001792 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001793 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1794 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001795
1796 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001797 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001798 }
1799
John McCallf7a1a742009-11-24 19:00:30 +00001800 if (TemplateArgs)
1801 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001802
John McCallf7a1a742009-11-24 19:00:30 +00001803 return BuildDeclarationNameExpr(SS, R, ADL);
1804}
1805
John McCall129e2df2009-11-30 22:42:35 +00001806/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1807/// declaration name, generally during template instantiation.
1808/// There's a large number of things which don't need to be done along
1809/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001810ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001811Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001812 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001813 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001814 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001815 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001816
John McCall77bb1aa2010-05-01 00:40:08 +00001817 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001818 return ExprError();
1819
Abramo Bagnara25777432010-08-11 22:01:17 +00001820 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001821 LookupQualifiedName(R, DC);
1822
1823 if (R.isAmbiguous())
1824 return ExprError();
1825
1826 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001827 Diag(NameInfo.getLoc(), diag::err_no_member)
1828 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001829 return ExprError();
1830 }
1831
1832 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1833}
1834
1835/// LookupInObjCMethod - The parser has read a name in, and Sema has
1836/// detected that we're currently inside an ObjC method. Perform some
1837/// additional lookup.
1838///
1839/// Ideally, most of this would be done by lookup, but there's
1840/// actually quite a lot of extra work involved.
1841///
1842/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001843ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001844Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001845 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001846 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001847 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001848
John McCallf7a1a742009-11-24 19:00:30 +00001849 // There are two cases to handle here. 1) scoped lookup could have failed,
1850 // in which case we should look for an ivar. 2) scoped lookup could have
1851 // found a decl, but that decl is outside the current instance method (i.e.
1852 // a global variable). In these two cases, we do a lookup for an ivar with
1853 // this name, if the lookup sucedes, we replace it our current decl.
1854
1855 // If we're in a class method, we don't normally want to look for
1856 // ivars. But if we don't find anything else, and there's an
1857 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001858 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001859
1860 bool LookForIvars;
1861 if (Lookup.empty())
1862 LookForIvars = true;
1863 else if (IsClassMethod)
1864 LookForIvars = false;
1865 else
1866 LookForIvars = (Lookup.isSingleResult() &&
1867 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001868 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001869 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001870 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001871 ObjCInterfaceDecl *ClassDeclared;
1872 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1873 // Diagnose using an ivar in a class method.
1874 if (IsClassMethod)
1875 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1876 << IV->getDeclName());
1877
1878 // If we're referencing an invalid decl, just return this as a silent
1879 // error node. The error diagnostic was already emitted on the decl.
1880 if (IV->isInvalidDecl())
1881 return ExprError();
1882
1883 // Check if referencing a field with __attribute__((deprecated)).
1884 if (DiagnoseUseOfDecl(IV, Loc))
1885 return ExprError();
1886
1887 // Diagnose the use of an ivar outside of the declaring class.
1888 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1889 ClassDeclared != IFace)
1890 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1891
1892 // FIXME: This should use a new expr for a direct reference, don't
1893 // turn this into Self->ivar, just return a BareIVarExpr or something.
1894 IdentifierInfo &II = Context.Idents.get("self");
1895 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001896 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001897 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00001898 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00001899 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001900 SelfName, false, false);
1901 if (SelfExpr.isInvalid())
1902 return ExprError();
1903
John Wiegley429bb272011-04-08 18:41:53 +00001904 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1905 if (SelfExpr.isInvalid())
1906 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001907
John McCallf7a1a742009-11-24 19:00:30 +00001908 MarkDeclarationReferenced(Loc, IV);
1909 return Owned(new (Context)
1910 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00001911 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001912 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001913 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001914 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001915 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001916 ObjCInterfaceDecl *ClassDeclared;
1917 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1918 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1919 IFace == ClassDeclared)
1920 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1921 }
1922 }
1923
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001924 if (Lookup.empty() && II && AllowBuiltinCreation) {
1925 // FIXME. Consolidate this with similar code in LookupName.
1926 if (unsigned BuiltinID = II->getBuiltinID()) {
1927 if (!(getLangOptions().CPlusPlus &&
1928 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1929 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1930 S, Lookup.isForRedeclaration(),
1931 Lookup.getNameLoc());
1932 if (D) Lookup.addDecl(D);
1933 }
1934 }
1935 }
John McCallf7a1a742009-11-24 19:00:30 +00001936 // Sentinel value saying that we didn't do anything special.
1937 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001938}
John McCallba135432009-11-21 08:51:07 +00001939
John McCall6bb80172010-03-30 21:47:33 +00001940/// \brief Cast a base object to a member's actual type.
1941///
1942/// Logically this happens in three phases:
1943///
1944/// * First we cast from the base type to the naming class.
1945/// The naming class is the class into which we were looking
1946/// when we found the member; it's the qualifier type if a
1947/// qualifier was provided, and otherwise it's the base type.
1948///
1949/// * Next we cast from the naming class to the declaring class.
1950/// If the member we found was brought into a class's scope by
1951/// a using declaration, this is that class; otherwise it's
1952/// the class declaring the member.
1953///
1954/// * Finally we cast from the declaring class to the "true"
1955/// declaring class of the member. This conversion does not
1956/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00001957ExprResult
1958Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001959 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001960 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001961 NamedDecl *Member) {
1962 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1963 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00001964 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001965
Douglas Gregor5fccd362010-03-03 23:55:11 +00001966 QualType DestRecordType;
1967 QualType DestType;
1968 QualType FromRecordType;
1969 QualType FromType = From->getType();
1970 bool PointerConversions = false;
1971 if (isa<FieldDecl>(Member)) {
1972 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001973
Douglas Gregor5fccd362010-03-03 23:55:11 +00001974 if (FromType->getAs<PointerType>()) {
1975 DestType = Context.getPointerType(DestRecordType);
1976 FromRecordType = FromType->getPointeeType();
1977 PointerConversions = true;
1978 } else {
1979 DestType = DestRecordType;
1980 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001981 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001982 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1983 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00001984 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001985
Douglas Gregor5fccd362010-03-03 23:55:11 +00001986 DestType = Method->getThisType(Context);
1987 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001988
Douglas Gregor5fccd362010-03-03 23:55:11 +00001989 if (FromType->getAs<PointerType>()) {
1990 FromRecordType = FromType->getPointeeType();
1991 PointerConversions = true;
1992 } else {
1993 FromRecordType = FromType;
1994 DestType = DestRecordType;
1995 }
1996 } else {
1997 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00001998 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00001999 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002000
Douglas Gregor5fccd362010-03-03 23:55:11 +00002001 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002002 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002003
Douglas Gregor5fccd362010-03-03 23:55:11 +00002004 // If the unqualified types are the same, no conversion is necessary.
2005 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002006 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002007
John McCall6bb80172010-03-30 21:47:33 +00002008 SourceRange FromRange = From->getSourceRange();
2009 SourceLocation FromLoc = FromRange.getBegin();
2010
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002011 ExprValueKind VK = From->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00002012
Douglas Gregor5fccd362010-03-03 23:55:11 +00002013 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002014 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002015 // class name.
2016 //
2017 // If the member was a qualified name and the qualified referred to a
2018 // specific base subobject type, we'll cast to that intermediate type
2019 // first and then to the object in which the member is declared. That allows
2020 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2021 //
2022 // class Base { public: int x; };
2023 // class Derived1 : public Base { };
2024 // class Derived2 : public Base { };
2025 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2026 //
2027 // void VeryDerived::f() {
2028 // x = 17; // error: ambiguous base subobjects
2029 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2030 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002031 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002032 QualType QType = QualType(Qualifier->getAsType(), 0);
2033 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2034 assert(QType->isRecordType() && "lookup done with non-record type");
2035
2036 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2037
2038 // In C++98, the qualifier type doesn't actually have to be a base
2039 // type of the object type, in which case we just ignore it.
2040 // Otherwise build the appropriate casts.
2041 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002042 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002043 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002044 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002045 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002046
Douglas Gregor5fccd362010-03-03 23:55:11 +00002047 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002048 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002049 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2050 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002051
2052 FromType = QType;
2053 FromRecordType = QRecordType;
2054
2055 // If the qualifier type was the same as the destination type,
2056 // we're done.
2057 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002058 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002059 }
2060 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002061
John McCall6bb80172010-03-30 21:47:33 +00002062 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002063
John McCall6bb80172010-03-30 21:47:33 +00002064 // If we actually found the member through a using declaration, cast
2065 // down to the using declaration's type.
2066 //
2067 // Pointer equality is fine here because only one declaration of a
2068 // class ever has member declarations.
2069 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2070 assert(isa<UsingShadowDecl>(FoundDecl));
2071 QualType URecordType = Context.getTypeDeclType(
2072 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2073
2074 // We only need to do this if the naming-class to declaring-class
2075 // conversion is non-trivial.
2076 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2077 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002078 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002079 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002080 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002081 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002082
John McCall6bb80172010-03-30 21:47:33 +00002083 QualType UType = URecordType;
2084 if (PointerConversions)
2085 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002086 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2087 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002088 FromType = UType;
2089 FromRecordType = URecordType;
2090 }
2091
2092 // We don't do access control for the conversion from the
2093 // declaring class to the true declaring class.
2094 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002095 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002096
John McCallf871d0c2010-08-07 06:22:56 +00002097 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002098 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2099 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002100 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002101 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002102
John Wiegley429bb272011-04-08 18:41:53 +00002103 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2104 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002105}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002106
John McCallf7a1a742009-11-24 19:00:30 +00002107bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002108 const LookupResult &R,
2109 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002110 // Only when used directly as the postfix-expression of a call.
2111 if (!HasTrailingLParen)
2112 return false;
2113
2114 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002115 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002116 return false;
2117
2118 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002119 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002120 return false;
2121
2122 // Turn off ADL when we find certain kinds of declarations during
2123 // normal lookup:
2124 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2125 NamedDecl *D = *I;
2126
2127 // C++0x [basic.lookup.argdep]p3:
2128 // -- a declaration of a class member
2129 // Since using decls preserve this property, we check this on the
2130 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002131 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002132 return false;
2133
2134 // C++0x [basic.lookup.argdep]p3:
2135 // -- a block-scope function declaration that is not a
2136 // using-declaration
2137 // NOTE: we also trigger this for function templates (in fact, we
2138 // don't check the decl type at all, since all other decl types
2139 // turn off ADL anyway).
2140 if (isa<UsingShadowDecl>(D))
2141 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2142 else if (D->getDeclContext()->isFunctionOrMethod())
2143 return false;
2144
2145 // C++0x [basic.lookup.argdep]p3:
2146 // -- a declaration that is neither a function or a function
2147 // template
2148 // And also for builtin functions.
2149 if (isa<FunctionDecl>(D)) {
2150 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2151
2152 // But also builtin functions.
2153 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2154 return false;
2155 } else if (!isa<FunctionTemplateDecl>(D))
2156 return false;
2157 }
2158
2159 return true;
2160}
2161
2162
John McCallba135432009-11-21 08:51:07 +00002163/// Diagnoses obvious problems with the use of the given declaration
2164/// as an expression. This is only actually called for lookups that
2165/// were not overloaded, and it doesn't promise that the declaration
2166/// will in fact be used.
2167static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002168 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002169 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2170 return true;
2171 }
2172
2173 if (isa<ObjCInterfaceDecl>(D)) {
2174 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2175 return true;
2176 }
2177
2178 if (isa<NamespaceDecl>(D)) {
2179 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2180 return true;
2181 }
2182
2183 return false;
2184}
2185
John McCall60d7b3a2010-08-24 06:29:42 +00002186ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002187Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002188 LookupResult &R,
2189 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002190 // If this is a single, fully-resolved result and we don't need ADL,
2191 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002192 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002193 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2194 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002195
2196 // We only need to check the declaration if there's exactly one
2197 // result, because in the overloaded case the results can only be
2198 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002199 if (R.isSingleResult() &&
2200 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002201 return ExprError();
2202
John McCallc373d482010-01-27 01:50:18 +00002203 // Otherwise, just build an unresolved lookup expression. Suppress
2204 // any lookup-related diagnostics; we'll hash these out later, when
2205 // we've picked a target.
2206 R.suppressDiagnostics();
2207
John McCallba135432009-11-21 08:51:07 +00002208 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002209 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002210 SS.getWithLocInContext(Context),
2211 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002212 NeedsADL, R.isOverloadedResult(),
2213 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002214
2215 return Owned(ULE);
2216}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002217
John McCallba135432009-11-21 08:51:07 +00002218/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002219ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002220Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002221 const DeclarationNameInfo &NameInfo,
2222 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002223 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002224 assert(!isa<FunctionTemplateDecl>(D) &&
2225 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002226
Abramo Bagnara25777432010-08-11 22:01:17 +00002227 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002228 if (CheckDeclInExpr(*this, Loc, D))
2229 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002230
Douglas Gregor9af2f522009-12-01 16:58:18 +00002231 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2232 // Specifically diagnose references to class templates that are missing
2233 // a template argument list.
2234 Diag(Loc, diag::err_template_decl_ref)
2235 << Template << SS.getRange();
2236 Diag(Template->getLocation(), diag::note_template_decl_here);
2237 return ExprError();
2238 }
2239
2240 // Make sure that we're referring to a value.
2241 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2242 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002243 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002244 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002245 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002246 return ExprError();
2247 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002248
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002249 // Check whether this declaration can be used. Note that we suppress
2250 // this check when we're going to perform argument-dependent lookup
2251 // on this function name, because this might not be the function
2252 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002253 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002254 return ExprError();
2255
Steve Naroffdd972f22008-09-05 22:11:13 +00002256 // Only create DeclRefExpr's for valid Decl's.
2257 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002258 return ExprError();
2259
John McCall5808ce42011-02-03 08:15:49 +00002260 // Handle members of anonymous structs and unions. If we got here,
2261 // and the reference is to a class member indirect field, then this
2262 // must be the subject of a pointer-to-member expression.
2263 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2264 if (!indirectField->isCXXClassMember())
2265 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2266 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002267
Chris Lattner639e2d32008-10-20 05:16:36 +00002268 // If the identifier reference is inside a block, and it refers to a value
2269 // that is outside the block, create a BlockDeclRefExpr instead of a
2270 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2271 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002272 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002273 // We do not do this for things like enum constants, global variables, etc,
2274 // as they do not get snapshotted.
2275 //
John McCall6b5a61b2011-02-07 10:33:21 +00002276 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002277 case CR_Error:
2278 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002279
John McCall469a1eb2011-02-02 13:00:07 +00002280 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002281 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2282 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2283
2284 case CR_CaptureByRef:
2285 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2286 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002287
2288 case CR_NoCapture: {
2289 // If this reference is not in a block or if the referenced
2290 // variable is within the block, create a normal DeclRefExpr.
2291
2292 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002293 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002294
2295 switch (D->getKind()) {
2296 // Ignore all the non-ValueDecl kinds.
2297#define ABSTRACT_DECL(kind)
2298#define VALUE(type, base)
2299#define DECL(type, base) \
2300 case Decl::type:
2301#include "clang/AST/DeclNodes.inc"
2302 llvm_unreachable("invalid value decl kind");
2303 return ExprError();
2304
2305 // These shouldn't make it here.
2306 case Decl::ObjCAtDefsField:
2307 case Decl::ObjCIvar:
2308 llvm_unreachable("forming non-member reference to ivar?");
2309 return ExprError();
2310
2311 // Enum constants are always r-values and never references.
2312 // Unresolved using declarations are dependent.
2313 case Decl::EnumConstant:
2314 case Decl::UnresolvedUsingValue:
2315 valueKind = VK_RValue;
2316 break;
2317
2318 // Fields and indirect fields that got here must be for
2319 // pointer-to-member expressions; we just call them l-values for
2320 // internal consistency, because this subexpression doesn't really
2321 // exist in the high-level semantics.
2322 case Decl::Field:
2323 case Decl::IndirectField:
2324 assert(getLangOptions().CPlusPlus &&
2325 "building reference to field in C?");
2326
2327 // These can't have reference type in well-formed programs, but
2328 // for internal consistency we do this anyway.
2329 type = type.getNonReferenceType();
2330 valueKind = VK_LValue;
2331 break;
2332
2333 // Non-type template parameters are either l-values or r-values
2334 // depending on the type.
2335 case Decl::NonTypeTemplateParm: {
2336 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2337 type = reftype->getPointeeType();
2338 valueKind = VK_LValue; // even if the parameter is an r-value reference
2339 break;
2340 }
2341
2342 // For non-references, we need to strip qualifiers just in case
2343 // the template parameter was declared as 'const int' or whatever.
2344 valueKind = VK_RValue;
2345 type = type.getUnqualifiedType();
2346 break;
2347 }
2348
2349 case Decl::Var:
2350 // In C, "extern void blah;" is valid and is an r-value.
2351 if (!getLangOptions().CPlusPlus &&
2352 !type.hasQualifiers() &&
2353 type->isVoidType()) {
2354 valueKind = VK_RValue;
2355 break;
2356 }
2357 // fallthrough
2358
2359 case Decl::ImplicitParam:
2360 case Decl::ParmVar:
2361 // These are always l-values.
2362 valueKind = VK_LValue;
2363 type = type.getNonReferenceType();
2364 break;
2365
2366 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002367 const FunctionType *fty = type->castAs<FunctionType>();
2368
2369 // If we're referring to a function with an __unknown_anytype
2370 // result type, make the entire expression __unknown_anytype.
2371 if (fty->getResultType() == Context.UnknownAnyTy) {
2372 type = Context.UnknownAnyTy;
2373 valueKind = VK_RValue;
2374 break;
2375 }
2376
John McCall76a40212011-02-09 01:13:10 +00002377 // Functions are l-values in C++.
2378 if (getLangOptions().CPlusPlus) {
2379 valueKind = VK_LValue;
2380 break;
2381 }
2382
2383 // C99 DR 316 says that, if a function type comes from a
2384 // function definition (without a prototype), that type is only
2385 // used for checking compatibility. Therefore, when referencing
2386 // the function, we pretend that we don't have the full function
2387 // type.
John McCall755d8492011-04-12 00:42:48 +00002388 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2389 isa<FunctionProtoType>(fty))
2390 type = Context.getFunctionNoProtoType(fty->getResultType(),
2391 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002392
2393 // Functions are r-values in C.
2394 valueKind = VK_RValue;
2395 break;
2396 }
2397
2398 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002399 // If we're referring to a method with an __unknown_anytype
2400 // result type, make the entire expression __unknown_anytype.
2401 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002402 if (const FunctionProtoType *proto
2403 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002404 if (proto->getResultType() == Context.UnknownAnyTy) {
2405 type = Context.UnknownAnyTy;
2406 valueKind = VK_RValue;
2407 break;
2408 }
2409
John McCall76a40212011-02-09 01:13:10 +00002410 // C++ methods are l-values if static, r-values if non-static.
2411 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2412 valueKind = VK_LValue;
2413 break;
2414 }
2415 // fallthrough
2416
2417 case Decl::CXXConversion:
2418 case Decl::CXXDestructor:
2419 case Decl::CXXConstructor:
2420 valueKind = VK_RValue;
2421 break;
2422 }
2423
2424 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2425 }
2426
John McCall469a1eb2011-02-02 13:00:07 +00002427 }
John McCallf89e55a2010-11-18 06:31:45 +00002428
John McCall6b5a61b2011-02-07 10:33:21 +00002429 llvm_unreachable("unknown capture result");
2430 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002431}
2432
John McCall755d8492011-04-12 00:42:48 +00002433ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002434 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002435
Reid Spencer5f016e22007-07-11 17:01:13 +00002436 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002437 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002438 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2439 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2440 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002441 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002442
Chris Lattnerfa28b302008-01-12 08:14:25 +00002443 // Pre-defined identifiers are of type char[x], where x is the length of the
2444 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002445
Anders Carlsson3a082d82009-09-08 18:24:21 +00002446 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002447 if (!currentDecl && getCurBlock())
2448 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002449 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002450 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002451 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002452 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002453
Anders Carlsson773f3972009-09-11 01:22:35 +00002454 QualType ResTy;
2455 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2456 ResTy = Context.DependentTy;
2457 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002458 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002459
Anders Carlsson773f3972009-09-11 01:22:35 +00002460 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002461 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002462 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2463 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002464 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002465}
2466
John McCall60d7b3a2010-08-24 06:29:42 +00002467ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002468 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002469 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002470 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002471 if (Invalid)
2472 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002473
Benjamin Kramerddeea562010-02-27 13:44:12 +00002474 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002475 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002476 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002477 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002478
Chris Lattnere8337df2009-12-30 21:19:39 +00002479 QualType Ty;
2480 if (!getLangOptions().CPlusPlus)
2481 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2482 else if (Literal.isWide())
2483 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002484 else if (Literal.isUTF16())
2485 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2486 else if (Literal.isUTF32())
2487 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002488 else if (Literal.isMultiChar())
2489 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002490 else
2491 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002492
Douglas Gregor5cee1192011-07-27 05:40:30 +00002493 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2494 if (Literal.isWide())
2495 Kind = CharacterLiteral::Wide;
2496 else if (Literal.isUTF16())
2497 Kind = CharacterLiteral::UTF16;
2498 else if (Literal.isUTF32())
2499 Kind = CharacterLiteral::UTF32;
2500
2501 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2502 Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002503}
2504
John McCall60d7b3a2010-08-24 06:29:42 +00002505ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002506 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002507 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2508 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002509 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002510 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002511 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002512 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002513 }
Ted Kremenek28396602009-01-13 23:19:12 +00002514
Reid Spencer5f016e22007-07-11 17:01:13 +00002515 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002516 // Add padding so that NumericLiteralParser can overread by one character.
2517 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002518 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002519
Reid Spencer5f016e22007-07-11 17:01:13 +00002520 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002521 bool Invalid = false;
2522 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2523 if (Invalid)
2524 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002525
Mike Stump1eb44332009-09-09 15:08:12 +00002526 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002527 Tok.getLocation(), PP);
2528 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002529 return ExprError();
2530
Chris Lattner5d661452007-08-26 03:42:43 +00002531 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002532
Chris Lattner5d661452007-08-26 03:42:43 +00002533 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002534 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002535 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002536 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002537 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002538 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002539 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002540 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002541
2542 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2543
John McCall94c939d2009-12-24 09:08:04 +00002544 using llvm::APFloat;
2545 APFloat Val(Format);
2546
2547 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002548
2549 // Overflow is always an error, but underflow is only an error if
2550 // we underflowed to zero (APFloat reports denormals as underflow).
2551 if ((result & APFloat::opOverflow) ||
2552 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002553 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002554 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002555 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002556 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002557 APFloat::getLargest(Format).toString(buffer);
2558 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002559 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002560 APFloat::getSmallest(Format).toString(buffer);
2561 }
2562
2563 Diag(Tok.getLocation(), diagnostic)
2564 << Ty
Chris Lattner5f9e2722011-07-23 10:55:15 +00002565 << StringRef(buffer.data(), buffer.size());
John McCall94c939d2009-12-24 09:08:04 +00002566 }
2567
2568 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002569 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002570
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002571 if (Ty == Context.DoubleTy) {
2572 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002573 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002574 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2575 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002576 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002577 }
2578 }
Chris Lattner5d661452007-08-26 03:42:43 +00002579 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002580 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002581 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002582 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002583
Neil Boothb9449512007-08-29 22:00:19 +00002584 // long long is a C99 feature.
2585 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002586 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002587 Diag(Tok.getLocation(), diag::ext_longlong);
2588
Reid Spencer5f016e22007-07-11 17:01:13 +00002589 // Get the value in the widest-possible width.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002590 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002591
Reid Spencer5f016e22007-07-11 17:01:13 +00002592 if (Literal.GetIntegerValue(ResultVal)) {
2593 // If this value didn't fit into uintmax_t, warn and force to ull.
2594 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002595 Ty = Context.UnsignedLongLongTy;
2596 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002597 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002598 } else {
2599 // If this value fits into a ULL, try to figure out what else it fits into
2600 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002601
Reid Spencer5f016e22007-07-11 17:01:13 +00002602 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2603 // be an unsigned int.
2604 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2605
2606 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002607 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002608 if (!Literal.isLong && !Literal.isLongLong) {
2609 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002610 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002611
Reid Spencer5f016e22007-07-11 17:01:13 +00002612 // Does it fit in a unsigned int?
2613 if (ResultVal.isIntN(IntSize)) {
2614 // Does it fit in a signed int?
2615 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002616 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002617 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002618 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002619 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002620 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002621 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002622
Reid Spencer5f016e22007-07-11 17:01:13 +00002623 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002624 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002625 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002626
Reid Spencer5f016e22007-07-11 17:01:13 +00002627 // Does it fit in a unsigned long?
2628 if (ResultVal.isIntN(LongSize)) {
2629 // Does it fit in a signed long?
2630 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002631 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002632 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002633 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002634 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002635 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002636 }
2637
Reid Spencer5f016e22007-07-11 17:01:13 +00002638 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002639 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002640 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002641
Reid Spencer5f016e22007-07-11 17:01:13 +00002642 // Does it fit in a unsigned long long?
2643 if (ResultVal.isIntN(LongLongSize)) {
2644 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002645 // To be compatible with MSVC, hex integer literals ending with the
2646 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002647 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
Francois Pichet62ec1f22011-09-17 17:15:52 +00002648 (getLangOptions().MicrosoftExt && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002649 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002650 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002651 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002652 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002653 }
2654 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002655
Reid Spencer5f016e22007-07-11 17:01:13 +00002656 // If we still couldn't decide a type, we probably have something that
2657 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002658 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002659 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002660 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002661 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002662 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002663
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002664 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002665 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002666 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002667 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002668 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002669
Chris Lattner5d661452007-08-26 03:42:43 +00002670 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2671 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002672 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002673 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002674
2675 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002676}
2677
Richard Trieuccd891a2011-09-09 01:45:06 +00002678ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002679 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002680 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002681}
2682
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002683static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2684 SourceLocation Loc,
2685 SourceRange ArgRange) {
2686 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2687 // scalar or vector data type argument..."
2688 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2689 // type (C99 6.2.5p18) or void.
2690 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2691 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2692 << T << ArgRange;
2693 return true;
2694 }
2695
2696 assert((T->isVoidType() || !T->isIncompleteType()) &&
2697 "Scalar types should always be complete");
2698 return false;
2699}
2700
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002701static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2702 SourceLocation Loc,
2703 SourceRange ArgRange,
2704 UnaryExprOrTypeTrait TraitKind) {
2705 // C99 6.5.3.4p1:
2706 if (T->isFunctionType()) {
2707 // alignof(function) is allowed as an extension.
2708 if (TraitKind == UETT_SizeOf)
2709 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2710 return false;
2711 }
2712
2713 // Allow sizeof(void)/alignof(void) as an extension.
2714 if (T->isVoidType()) {
2715 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2716 return false;
2717 }
2718
2719 return true;
2720}
2721
2722static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2723 SourceLocation Loc,
2724 SourceRange ArgRange,
2725 UnaryExprOrTypeTrait TraitKind) {
2726 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2727 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2728 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2729 << T << (TraitKind == UETT_SizeOf)
2730 << ArgRange;
2731 return true;
2732 }
2733
2734 return false;
2735}
2736
Chandler Carruth9d342d02011-05-26 08:53:10 +00002737/// \brief Check the constrains on expression operands to unary type expression
2738/// and type traits.
2739///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002740/// Completes any types necessary and validates the constraints on the operand
2741/// expression. The logic mostly mirrors the type-based overload, but may modify
2742/// the expression as it completes the type for that expression through template
2743/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00002744bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002745 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002746 QualType ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002747
2748 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2749 // the result is the size of the referenced type."
2750 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2751 // result shall be the alignment of the referenced type."
2752 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2753 ExprTy = Ref->getPointeeType();
2754
2755 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00002756 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2757 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002758
2759 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00002760 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2761 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002762 return false;
2763
Richard Trieuccd891a2011-09-09 01:45:06 +00002764 if (RequireCompleteExprType(E,
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002765 PDiag(diag::err_sizeof_alignof_incomplete_type)
Richard Trieuccd891a2011-09-09 01:45:06 +00002766 << ExprKind << E->getSourceRange(),
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002767 std::make_pair(SourceLocation(), PDiag(0))))
2768 return true;
2769
2770 // Completeing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00002771 ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002772 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2773 ExprTy = Ref->getPointeeType();
2774
Richard Trieuccd891a2011-09-09 01:45:06 +00002775 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2776 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002777 return true;
2778
Nico Webercf739922011-06-15 02:47:03 +00002779 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002780 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00002781 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2782 QualType OType = PVD->getOriginalType();
2783 QualType Type = PVD->getType();
2784 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002785 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00002786 << Type << OType;
2787 Diag(PVD->getLocation(), diag::note_declared_at);
2788 }
2789 }
2790 }
2791 }
2792
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002793 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00002794}
2795
2796/// \brief Check the constraints on operands to unary expression and type
2797/// traits.
2798///
2799/// This will complete any types necessary, and validate the various constraints
2800/// on those operands.
2801///
Reid Spencer5f016e22007-07-11 17:01:13 +00002802/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002803/// C99 6.3.2.1p[2-4] all state:
2804/// Except when it is the operand of the sizeof operator ...
2805///
2806/// C++ [expr.sizeof]p4
2807/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2808/// standard conversions are not applied to the operand of sizeof.
2809///
2810/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00002811bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002812 SourceLocation OpLoc,
2813 SourceRange ExprRange,
2814 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002815 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00002816 return false;
2817
Sebastian Redl5d484e82009-11-23 17:18:46 +00002818 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2819 // the result is the size of the referenced type."
2820 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2821 // result shall be the alignment of the referenced type."
Richard Trieuccd891a2011-09-09 01:45:06 +00002822 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2823 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00002824
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002825 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00002826 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002827
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002828 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00002829 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002830 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00002831 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002832
Richard Trieuccd891a2011-09-09 01:45:06 +00002833 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002834 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002835 << ExprKind << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002836 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002837
Richard Trieuccd891a2011-09-09 01:45:06 +00002838 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002839 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00002840 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002841
Chris Lattner1efaa952009-04-24 00:30:45 +00002842 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002843}
2844
Chandler Carruth9d342d02011-05-26 08:53:10 +00002845static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00002846 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002847
Mike Stump1eb44332009-09-09 15:08:12 +00002848 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002849 if (isa<DeclRefExpr>(E))
2850 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002851
2852 // Cannot know anything else if the expression is dependent.
2853 if (E->isTypeDependent())
2854 return false;
2855
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002856 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002857 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2858 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002859 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002860 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002861
2862 // Alignment of a field access is always okay, so long as it isn't a
2863 // bit-field.
2864 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002865 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002866 return false;
2867
Chandler Carruth9d342d02011-05-26 08:53:10 +00002868 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002869}
2870
Chandler Carruth9d342d02011-05-26 08:53:10 +00002871bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002872 E = E->IgnoreParens();
2873
2874 // Cannot know anything else if the expression is dependent.
2875 if (E->isTypeDependent())
2876 return false;
2877
Chandler Carruth9d342d02011-05-26 08:53:10 +00002878 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00002879}
2880
Douglas Gregorba498172009-03-13 21:01:28 +00002881/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002882ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002883Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2884 SourceLocation OpLoc,
2885 UnaryExprOrTypeTrait ExprKind,
2886 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002887 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002888 return ExprError();
2889
John McCalla93c9342009-12-07 02:54:59 +00002890 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002891
Douglas Gregorba498172009-03-13 21:01:28 +00002892 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002893 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00002894 return ExprError();
2895
2896 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002897 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2898 Context.getSizeType(),
2899 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002900}
2901
2902/// \brief Build a sizeof or alignof expression given an expression
2903/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002904ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002905Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2906 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00002907 ExprResult PE = CheckPlaceholderExpr(E);
2908 if (PE.isInvalid())
2909 return ExprError();
2910
2911 E = PE.get();
2912
Douglas Gregorba498172009-03-13 21:01:28 +00002913 // Verify that the operand is valid.
2914 bool isInvalid = false;
2915 if (E->isTypeDependent()) {
2916 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002917 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002918 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002919 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002920 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002921 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002922 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00002923 isInvalid = true;
2924 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002925 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00002926 }
2927
2928 if (isInvalid)
2929 return ExprError();
2930
2931 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002932 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002933 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002934 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002935}
2936
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002937/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2938/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00002939/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00002940ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002941Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00002942 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002943 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002944 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002945 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002946
Richard Trieuccd891a2011-09-09 01:45:06 +00002947 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00002948 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00002949 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002950 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002951 }
Sebastian Redl05189992008-11-11 17:56:53 +00002952
Douglas Gregorba498172009-03-13 21:01:28 +00002953 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002954 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregorba498172009-03-13 21:01:28 +00002955 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002956}
2957
John Wiegley429bb272011-04-08 18:41:53 +00002958static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00002959 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00002960 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00002961 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002962
John McCallf6a16482010-12-04 03:47:34 +00002963 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00002964 if (V.get()->getObjectKind() != OK_Ordinary) {
2965 V = S.DefaultLvalueConversion(V.take());
2966 if (V.isInvalid())
2967 return QualType();
2968 }
John McCallf6a16482010-12-04 03:47:34 +00002969
Chris Lattnercc26ed72007-08-26 05:39:26 +00002970 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00002971 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002972 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002973
Chris Lattnercc26ed72007-08-26 05:39:26 +00002974 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00002975 if (V.get()->getType()->isArithmeticType())
2976 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002977
John McCall2cd11fe2010-10-12 02:09:17 +00002978 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00002979 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00002980 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00002981 if (PR.get() != V.get()) {
2982 V = move(PR);
Richard Trieuccd891a2011-09-09 01:45:06 +00002983 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00002984 }
2985
Chris Lattnercc26ed72007-08-26 05:39:26 +00002986 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00002987 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00002988 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00002989 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00002990}
2991
2992
Reid Spencer5f016e22007-07-11 17:01:13 +00002993
John McCall60d7b3a2010-08-24 06:29:42 +00002994ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00002995Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002996 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00002997 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00002998 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002999 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003000 case tok::plusplus: Opc = UO_PostInc; break;
3001 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003002 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003003
John McCall9ae2f072010-08-23 23:25:46 +00003004 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003005}
3006
John McCall60d7b3a2010-08-24 06:29:42 +00003007ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003008Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3009 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003010 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003011 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003012 if (Result.isInvalid()) return ExprError();
3013 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003014
John McCall9ae2f072010-08-23 23:25:46 +00003015 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003016
Douglas Gregor337c6b92008-11-19 17:17:41 +00003017 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003018 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003019 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003020 Context.DependentTy,
3021 VK_LValue, OK_Ordinary,
3022 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003023 }
3024
Mike Stump1eb44332009-09-09 15:08:12 +00003025 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003026 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003027 LHSExp->getType()->isEnumeralType() ||
3028 RHSExp->getType()->isRecordType() ||
3029 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00003030 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003031 }
3032
John McCall9ae2f072010-08-23 23:25:46 +00003033 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003034}
3035
3036
John McCall60d7b3a2010-08-24 06:29:42 +00003037ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003038Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003039 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00003040 Expr *LHSExp = Base;
3041 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003042
Chris Lattner12d9ff62007-07-16 00:14:47 +00003043 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003044 if (!LHSExp->getType()->getAs<VectorType>()) {
3045 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3046 if (Result.isInvalid())
3047 return ExprError();
3048 LHSExp = Result.take();
3049 }
3050 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3051 if (Result.isInvalid())
3052 return ExprError();
3053 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003054
Chris Lattner12d9ff62007-07-16 00:14:47 +00003055 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003056 ExprValueKind VK = VK_LValue;
3057 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003058
Reid Spencer5f016e22007-07-11 17:01:13 +00003059 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003060 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003061 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003062 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003063 Expr *BaseExpr, *IndexExpr;
3064 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003065 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3066 BaseExpr = LHSExp;
3067 IndexExpr = RHSExp;
3068 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003069 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003070 BaseExpr = LHSExp;
3071 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003072 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003073 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00003074 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00003075 BaseExpr = RHSExp;
3076 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003077 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003078 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003079 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003080 BaseExpr = LHSExp;
3081 IndexExpr = RHSExp;
3082 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003083 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003084 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003085 // Handle the uncommon case of "123[Ptr]".
3086 BaseExpr = RHSExp;
3087 IndexExpr = LHSExp;
3088 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003089 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003090 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003091 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003092 VK = LHSExp->getValueKind();
3093 if (VK != VK_RValue)
3094 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003095
Chris Lattner12d9ff62007-07-16 00:14:47 +00003096 // FIXME: need to deal with const...
3097 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003098 } else if (LHSTy->isArrayType()) {
3099 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003100 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003101 // wasn't promoted because of the C90 rule that doesn't
3102 // allow promoting non-lvalue arrays. Warn, then
3103 // force the promotion here.
3104 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3105 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003106 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3107 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003108 LHSTy = LHSExp->getType();
3109
3110 BaseExpr = LHSExp;
3111 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003112 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003113 } else if (RHSTy->isArrayType()) {
3114 // Same as previous, except for 123[f().a] case
3115 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3116 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003117 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3118 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003119 RHSTy = RHSExp->getType();
3120
3121 BaseExpr = RHSExp;
3122 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003123 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003124 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003125 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3126 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003127 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003128 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003129 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003130 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3131 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003132
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003133 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003134 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3135 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003136 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3137
Douglas Gregore7450f52009-03-24 19:52:54 +00003138 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003139 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3140 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003141 // incomplete types are not object types.
3142 if (ResultType->isFunctionType()) {
3143 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3144 << ResultType << BaseExpr->getSourceRange();
3145 return ExprError();
3146 }
Mike Stump1eb44332009-09-09 15:08:12 +00003147
Abramo Bagnara46358452010-09-13 06:50:07 +00003148 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3149 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003150 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3151 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003152
3153 // C forbids expressions of unqualified void type from being l-values.
3154 // See IsCForbiddenLValueType.
3155 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003156 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003157 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003158 PDiag(diag::err_subscript_incomplete_type)
3159 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003160 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003161
Chris Lattner1efaa952009-04-24 00:30:45 +00003162 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003163 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003164 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3165 << ResultType << BaseExpr->getSourceRange();
3166 return ExprError();
3167 }
Mike Stump1eb44332009-09-09 15:08:12 +00003168
John McCall09431682010-11-18 19:01:18 +00003169 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003170 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003171
Mike Stumpeed9cac2009-02-19 03:04:26 +00003172 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003173 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003174}
3175
John McCall60d7b3a2010-08-24 06:29:42 +00003176ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003177 FunctionDecl *FD,
3178 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003179 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003180 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003181 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003182 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003183 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003184 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003185 return ExprError();
3186 }
3187
3188 if (Param->hasUninstantiatedDefaultArg()) {
3189 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003190
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003191 // Instantiate the expression.
3192 MultiLevelTemplateArgumentList ArgList
3193 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003194
Nico Weber08e41a62010-11-29 18:19:25 +00003195 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003196 = ArgList.getInnermost();
3197 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3198 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003199
Nico Weber08e41a62010-11-29 18:19:25 +00003200 ExprResult Result;
3201 {
3202 // C++ [dcl.fct.default]p5:
3203 // The names in the [default argument] expression are bound, and
3204 // the semantic constraints are checked, at the point where the
3205 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003206 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00003207 Result = SubstExpr(UninstExpr, ArgList);
3208 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003209 if (Result.isInvalid())
3210 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003211
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003212 // Check the expression as an initializer for the parameter.
3213 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003214 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003215 InitializationKind Kind
3216 = InitializationKind::CreateCopy(Param->getLocation(),
3217 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3218 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003219
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003220 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3221 Result = InitSeq.Perform(*this, Entity, Kind,
3222 MultiExprArg(*this, &ResultE, 1));
3223 if (Result.isInvalid())
3224 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003225
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003226 // Build the default argument expression.
3227 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3228 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003229 }
3230
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003231 // If the default expression creates temporaries, we need to
3232 // push them to the current stack of expression temporaries so they'll
3233 // be properly destroyed.
3234 // FIXME: We should really be rebuilding the default argument with new
3235 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003236 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3237 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3238 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3239 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3240 ExprTemporaries.push_back(Temporary);
John McCallf85e1932011-06-15 23:02:42 +00003241 ExprNeedsCleanups = true;
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003242 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003243
3244 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003245 // Just mark all of the declarations in this potentially-evaluated expression
3246 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003247 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00003248 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003249}
3250
Douglas Gregor88a35142008-12-22 05:46:06 +00003251/// ConvertArgumentsForCall - Converts the arguments specified in
3252/// Args/NumArgs to the parameter types of the function FDecl with
3253/// function prototype Proto. Call is the call expression itself, and
3254/// Fn is the function expression. For a C++ member function, this
3255/// routine does not attempt to convert the object argument. Returns
3256/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003257bool
3258Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003259 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003260 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003261 Expr **Args, unsigned NumArgs,
3262 SourceLocation RParenLoc) {
John McCall8e10f3b2011-02-26 05:39:39 +00003263 // Bail out early if calling a builtin with custom typechecking.
3264 // We don't need to do this in the
3265 if (FDecl)
3266 if (unsigned ID = FDecl->getBuiltinID())
3267 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3268 return false;
3269
Mike Stumpeed9cac2009-02-19 03:04:26 +00003270 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003271 // assignment, to the types of the corresponding parameter, ...
3272 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003273 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003274
Douglas Gregor88a35142008-12-22 05:46:06 +00003275 // If too few arguments are available (and we don't have default
3276 // arguments for the remaining parameters), don't make the call.
3277 if (NumArgs < NumArgsInProto) {
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003278 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) {
3279 Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003280 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00003281 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003282
3283 // Emit the location of the prototype.
3284 if (FDecl && !FDecl->getBuiltinID())
3285 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3286 << FDecl;
3287
3288 return true;
3289 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003290 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003291 }
3292
3293 // If too many are passed and not variadic, error on the extras and drop
3294 // them.
3295 if (NumArgs > NumArgsInProto) {
3296 if (!Proto->isVariadic()) {
3297 Diag(Args[NumArgsInProto]->getLocStart(),
3298 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003299 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00003300 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00003301 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3302 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003303
3304 // Emit the location of the prototype.
3305 if (FDecl && !FDecl->getBuiltinID())
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003306 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3307 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003308
Douglas Gregor88a35142008-12-22 05:46:06 +00003309 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003310 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003311 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003312 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003313 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003314 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003315 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003316 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3317 if (Fn->getType()->isBlockPointerType())
3318 CallType = VariadicBlock; // Block
3319 else if (isa<MemberExpr>(Fn))
3320 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003321 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003322 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003323 if (Invalid)
3324 return true;
3325 unsigned TotalNumArgs = AllArgs.size();
3326 for (unsigned i = 0; i < TotalNumArgs; ++i)
3327 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003328
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003329 return false;
3330}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003331
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003332bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3333 FunctionDecl *FDecl,
3334 const FunctionProtoType *Proto,
3335 unsigned FirstProtoArg,
3336 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003337 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003338 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003339 unsigned NumArgsInProto = Proto->getNumArgs();
3340 unsigned NumArgsToCheck = NumArgs;
3341 bool Invalid = false;
3342 if (NumArgs != NumArgsInProto)
3343 // Use default arguments for missing arguments
3344 NumArgsToCheck = NumArgsInProto;
3345 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003346 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003347 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003348 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003349
Douglas Gregor88a35142008-12-22 05:46:06 +00003350 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003351 if (ArgIx < NumArgs) {
3352 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003353
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003354 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3355 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003356 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003357 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003358 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003359
Douglas Gregora188ff22009-12-22 16:09:06 +00003360 // Pass the argument
3361 ParmVarDecl *Param = 0;
3362 if (FDecl && i < FDecl->getNumParams())
3363 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003364
Douglas Gregora188ff22009-12-22 16:09:06 +00003365 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003366 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003367 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3368 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003369 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003370 SourceLocation(),
3371 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00003372 if (ArgE.isInvalid())
3373 return true;
3374
3375 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003376 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003377 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003378
John McCall60d7b3a2010-08-24 06:29:42 +00003379 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003380 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003381 if (ArgExpr.isInvalid())
3382 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003383
Anders Carlsson56c5e332009-08-25 03:49:14 +00003384 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003385 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003386
3387 // Check for array bounds violations for each argument to the call. This
3388 // check only triggers warnings when the argument isn't a more complex Expr
3389 // with its own checking, such as a BinaryOperator.
3390 CheckArrayAccess(Arg);
3391
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003392 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003393 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003394
Douglas Gregor88a35142008-12-22 05:46:06 +00003395 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003396 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003397
3398 // Assume that extern "C" functions with variadic arguments that
3399 // return __unknown_anytype aren't *really* variadic.
3400 if (Proto->getResultType() == Context.UnknownAnyTy &&
3401 FDecl && FDecl->isExternC()) {
3402 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3403 ExprResult arg;
3404 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3405 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3406 else
3407 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3408 Invalid |= arg.isInvalid();
3409 AllArgs.push_back(arg.take());
3410 }
3411
3412 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3413 } else {
3414 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003415 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3416 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003417 Invalid |= Arg.isInvalid();
3418 AllArgs.push_back(Arg.take());
3419 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003420 }
Ted Kremenek615eb7c2011-09-26 23:36:13 +00003421
3422 // Check for array bounds violations.
3423 for (unsigned i = ArgIx; i != NumArgs; ++i)
3424 CheckArrayAccess(Args[i]);
Douglas Gregor88a35142008-12-22 05:46:06 +00003425 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003426 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003427}
3428
John McCall755d8492011-04-12 00:42:48 +00003429/// Given a function expression of unknown-any type, try to rebuild it
3430/// to have a function type.
3431static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3432
Steve Narofff69936d2007-09-16 03:34:24 +00003433/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003434/// This provides the location of the left/right parens and a list of comma
3435/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003436ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003437Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003438 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003439 Expr *ExecConfig) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003440 unsigned NumArgs = ArgExprs.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003441
3442 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003443 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003444 if (Result.isInvalid()) return ExprError();
3445 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003446
Richard Trieuccd891a2011-09-09 01:45:06 +00003447 Expr **Args = ArgExprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003448
Douglas Gregor88a35142008-12-22 05:46:06 +00003449 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003450 // If this is a pseudo-destructor expression, build the call immediately.
3451 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3452 if (NumArgs > 0) {
3453 // Pseudo-destructor calls should not have any arguments.
3454 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003455 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003456 SourceRange(Args[0]->getLocStart(),
3457 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003458
Douglas Gregora71d8192009-09-04 17:36:40 +00003459 NumArgs = 0;
3460 }
Mike Stump1eb44332009-09-09 15:08:12 +00003461
Douglas Gregora71d8192009-09-04 17:36:40 +00003462 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00003463 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003464 }
Mike Stump1eb44332009-09-09 15:08:12 +00003465
Douglas Gregor17330012009-02-04 15:01:18 +00003466 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003467 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003468 // FIXME: Will need to cache the results of name lookup (including ADL) in
3469 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003470 bool Dependent = false;
3471 if (Fn->isTypeDependent())
3472 Dependent = true;
3473 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3474 Dependent = true;
3475
Peter Collingbournee08ce652011-02-09 21:07:24 +00003476 if (Dependent) {
3477 if (ExecConfig) {
3478 return Owned(new (Context) CUDAKernelCallExpr(
3479 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3480 Context.DependentTy, VK_RValue, RParenLoc));
3481 } else {
3482 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3483 Context.DependentTy, VK_RValue,
3484 RParenLoc));
3485 }
3486 }
Douglas Gregor17330012009-02-04 15:01:18 +00003487
3488 // Determine whether this is a call to an object (C++ [over.call.object]).
3489 if (Fn->getType()->isRecordType())
3490 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003491 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003492
John McCall755d8492011-04-12 00:42:48 +00003493 if (Fn->getType() == Context.UnknownAnyTy) {
3494 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3495 if (result.isInvalid()) return ExprError();
3496 Fn = result.take();
3497 }
3498
John McCall864c0412011-04-26 20:42:42 +00003499 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00003500 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003501 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003502 }
John McCall864c0412011-04-26 20:42:42 +00003503 }
John McCall129e2df2009-11-30 22:42:35 +00003504
John McCall864c0412011-04-26 20:42:42 +00003505 // Check for overloaded calls. This can happen even in C due to extensions.
3506 if (Fn->getType() == Context.OverloadTy) {
3507 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3508
3509 // We aren't supposed to apply this logic if there's an '&' involved.
3510 if (!find.IsAddressOfOperand) {
3511 OverloadExpr *ovl = find.Expression;
3512 if (isa<UnresolvedLookupExpr>(ovl)) {
3513 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3514 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3515 RParenLoc, ExecConfig);
3516 } else {
John McCallaa81e162009-12-01 22:10:20 +00003517 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003518 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003519 }
3520 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003521 }
3522
Douglas Gregorfa047642009-02-04 00:32:51 +00003523 // If we're directly calling a function, get the appropriate declaration.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003524
Eli Friedmanefa42f72009-12-26 03:35:45 +00003525 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003526
John McCall3b4294e2009-12-16 12:17:52 +00003527 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003528 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3529 if (UnOp->getOpcode() == UO_AddrOf)
3530 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3531
John McCall3b4294e2009-12-16 12:17:52 +00003532 if (isa<DeclRefExpr>(NakedFn))
3533 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003534 else if (isa<MemberExpr>(NakedFn))
3535 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003536
Peter Collingbournee08ce652011-02-09 21:07:24 +00003537 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3538 ExecConfig);
3539}
3540
3541ExprResult
3542Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003543 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbournee08ce652011-02-09 21:07:24 +00003544 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3545 if (!ConfigDecl)
3546 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3547 << "cudaConfigureCall");
3548 QualType ConfigQTy = ConfigDecl->getType();
3549
3550 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3551 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3552
Richard Trieuccd891a2011-09-09 01:45:06 +00003553 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0);
John McCallaa81e162009-12-01 22:10:20 +00003554}
3555
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003556/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3557///
3558/// __builtin_astype( value, dst type )
3559///
Richard Trieuccd891a2011-09-09 01:45:06 +00003560ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003561 SourceLocation BuiltinLoc,
3562 SourceLocation RParenLoc) {
3563 ExprValueKind VK = VK_RValue;
3564 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00003565 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3566 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003567 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3568 return ExprError(Diag(BuiltinLoc,
3569 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003570 << DstTy
3571 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00003572 << E->getSourceRange());
3573 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieu67e29332011-08-02 04:35:43 +00003574 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003575}
3576
John McCall3b4294e2009-12-16 12:17:52 +00003577/// BuildResolvedCallExpr - Build a call to a resolved expression,
3578/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003579/// unary-convert to an expression of function-pointer or
3580/// block-pointer type.
3581///
3582/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003583ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003584Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3585 SourceLocation LParenLoc,
3586 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003587 SourceLocation RParenLoc,
3588 Expr *Config) {
John McCallaa81e162009-12-01 22:10:20 +00003589 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3590
Chris Lattner04421082008-04-08 04:40:51 +00003591 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00003592 ExprResult Result = UsualUnaryConversions(Fn);
3593 if (Result.isInvalid())
3594 return ExprError();
3595 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00003596
Chris Lattner925e60d2007-12-28 05:29:59 +00003597 // Make the call expr early, before semantic checks. This guarantees cleanup
3598 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00003599 CallExpr *TheCall;
3600 if (Config) {
3601 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3602 cast<CallExpr>(Config),
3603 Args, NumArgs,
3604 Context.BoolTy,
3605 VK_RValue,
3606 RParenLoc);
3607 } else {
3608 TheCall = new (Context) CallExpr(Context, Fn,
3609 Args, NumArgs,
3610 Context.BoolTy,
3611 VK_RValue,
3612 RParenLoc);
3613 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003614
John McCall8e10f3b2011-02-26 05:39:39 +00003615 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3616
3617 // Bail out early if calling a builtin with custom typechecking.
3618 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3619 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3620
John McCall1de4d4e2011-04-07 08:22:57 +00003621 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00003622 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00003623 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00003624 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3625 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00003626 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00003627 if (FuncT == 0)
3628 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3629 << Fn->getType() << Fn->getSourceRange());
3630 } else if (const BlockPointerType *BPT =
3631 Fn->getType()->getAs<BlockPointerType>()) {
3632 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3633 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00003634 // Handle calls to expressions of unknown-any type.
3635 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00003636 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003637 if (rewrite.isInvalid()) return ExprError();
3638 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00003639 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003640 goto retry;
3641 }
3642
Sebastian Redl0eb23302009-01-19 00:08:26 +00003643 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3644 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00003645 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003646
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003647 if (getLangOptions().CUDA) {
3648 if (Config) {
3649 // CUDA: Kernel calls must be to global functions
3650 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3651 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3652 << FDecl->getName() << Fn->getSourceRange());
3653
3654 // CUDA: Kernel function must have 'void' return type
3655 if (!FuncT->getResultType()->isVoidType())
3656 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3657 << Fn->getType() << Fn->getSourceRange());
3658 }
3659 }
3660
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003661 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003662 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00003663 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003664 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003665 return ExprError();
3666
Chris Lattner925e60d2007-12-28 05:29:59 +00003667 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003668 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00003669 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003670
Douglas Gregor72564e72009-02-26 23:50:07 +00003671 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00003672 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003673 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003674 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003675 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003676 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003677
Douglas Gregor74734d52009-04-02 15:37:10 +00003678 if (FDecl) {
3679 // Check if we have too few/too many template arguments, based
3680 // on our knowledge of the function definition.
3681 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00003682 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003683 const FunctionProtoType *Proto
3684 = Def->getType()->getAs<FunctionProtoType>();
3685 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003686 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3687 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003688 }
Douglas Gregor46542412010-10-25 20:39:23 +00003689
3690 // If the function we're calling isn't a function prototype, but we have
3691 // a function prototype from a prior declaratiom, use that prototype.
3692 if (!FDecl->hasPrototype())
3693 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00003694 }
3695
Steve Naroffb291ab62007-08-28 23:30:39 +00003696 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003697 for (unsigned i = 0; i != NumArgs; i++) {
3698 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00003699
3700 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003701 InitializedEntity Entity
3702 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00003703 Proto->getArgType(i),
3704 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00003705 ExprResult ArgE = PerformCopyInitialization(Entity,
3706 SourceLocation(),
3707 Owned(Arg));
3708 if (ArgE.isInvalid())
3709 return true;
3710
3711 Arg = ArgE.takeAs<Expr>();
3712
3713 } else {
John Wiegley429bb272011-04-08 18:41:53 +00003714 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3715
3716 if (ArgE.isInvalid())
3717 return true;
3718
3719 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00003720 }
3721
Douglas Gregor0700bbf2010-10-26 05:45:40 +00003722 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3723 Arg->getType(),
3724 PDiag(diag::err_call_incomplete_argument)
3725 << Arg->getSourceRange()))
3726 return ExprError();
3727
Chris Lattner925e60d2007-12-28 05:29:59 +00003728 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003729 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003730 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003731
Douglas Gregor88a35142008-12-22 05:46:06 +00003732 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3733 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003734 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3735 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003736
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003737 // Check for sentinels
3738 if (NDecl)
3739 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003740
Chris Lattner59907c42007-08-10 20:18:51 +00003741 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003742 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003743 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003744 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003745
John McCall8e10f3b2011-02-26 05:39:39 +00003746 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00003747 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00003748 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003749 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003750 return ExprError();
3751 }
Chris Lattner59907c42007-08-10 20:18:51 +00003752
John McCall9ae2f072010-08-23 23:25:46 +00003753 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00003754}
3755
John McCall60d7b3a2010-08-24 06:29:42 +00003756ExprResult
John McCallb3d87482010-08-24 05:47:05 +00003757Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00003758 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003759 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00003760 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003761 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00003762
3763 TypeSourceInfo *TInfo;
3764 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3765 if (!TInfo)
3766 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3767
John McCall9ae2f072010-08-23 23:25:46 +00003768 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00003769}
3770
John McCall60d7b3a2010-08-24 06:29:42 +00003771ExprResult
John McCall42f56b52010-01-18 19:35:47 +00003772Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00003773 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00003774 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00003775
Eli Friedman6223c222008-05-20 05:22:08 +00003776 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00003777 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3778 PDiag(diag::err_illegal_decl_array_incomplete_type)
3779 << SourceRange(LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003780 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00003781 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003782 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003783 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00003784 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003785 } else if (!literalType->isDependentType() &&
3786 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003787 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003788 << SourceRange(LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003789 LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003790 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003791
Douglas Gregor99a2e602009-12-16 01:38:02 +00003792 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003793 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003794 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00003795 = InitializationKind::CreateCStyleCast(LParenLoc,
3796 SourceRange(LParenLoc, RParenLoc));
Richard Trieuccd891a2011-09-09 01:45:06 +00003797 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00003798 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuccd891a2011-09-09 01:45:06 +00003799 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00003800 &literalType);
3801 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003802 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00003803 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00003804
Chris Lattner371f2582008-12-04 23:50:19 +00003805 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003806 if (isFileScope) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00003807 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003808 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003809 }
Eli Friedman08544622009-12-22 02:35:53 +00003810
John McCallf89e55a2010-11-18 06:31:45 +00003811 // In C, compound literals are l-values for some reason.
3812 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3813
Douglas Gregor751ec9b2011-06-17 04:59:12 +00003814 return MaybeBindToTemporary(
3815 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00003816 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003817}
3818
John McCall60d7b3a2010-08-24 06:29:42 +00003819ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00003820Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003821 SourceLocation RBraceLoc) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003822 unsigned NumInit = InitArgList.size();
3823 Expr **InitList = InitArgList.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003824
Steve Naroff08d92e42007-09-15 18:49:24 +00003825 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003826 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003827
Ted Kremenek709210f2010-04-13 23:39:13 +00003828 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3829 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003830 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003831 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003832}
3833
John McCalldc05b112011-09-10 01:16:55 +00003834/// Do an explicit extend of the given block pointer if we're in ARC.
3835static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
3836 assert(E.get()->getType()->isBlockPointerType());
3837 assert(E.get()->isRValue());
3838
3839 // Only do this in an r-value context.
3840 if (!S.getLangOptions().ObjCAutoRefCount) return;
3841
3842 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall33e56f32011-09-10 06:18:15 +00003843 CK_ARCExtendBlockObject, E.get(),
John McCalldc05b112011-09-10 01:16:55 +00003844 /*base path*/ 0, VK_RValue);
3845 S.ExprNeedsCleanups = true;
3846}
3847
3848/// Prepare a conversion of the given expression to an ObjC object
3849/// pointer type.
3850CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
3851 QualType type = E.get()->getType();
3852 if (type->isObjCObjectPointerType()) {
3853 return CK_BitCast;
3854 } else if (type->isBlockPointerType()) {
3855 maybeExtendBlockObject(*this, E);
3856 return CK_BlockPointerToObjCPointerCast;
3857 } else {
3858 assert(type->isPointerType());
3859 return CK_CPointerToObjCPointerCast;
3860 }
3861}
3862
John McCallf3ea8cf2010-11-14 08:17:51 +00003863/// Prepares for a scalar cast, performing all the necessary stages
3864/// except the final cast and returning the kind required.
John Wiegley429bb272011-04-08 18:41:53 +00003865static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00003866 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3867 // Also, callers should have filtered out the invalid cases with
3868 // pointers. Everything else should be possible.
3869
John Wiegley429bb272011-04-08 18:41:53 +00003870 QualType SrcTy = Src.get()->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00003871 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00003872 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00003873
John McCall1d9b3b22011-09-09 05:25:32 +00003874 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00003875 case Type::STK_MemberPointer:
3876 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003877
John McCall1d9b3b22011-09-09 05:25:32 +00003878 case Type::STK_CPointer:
3879 case Type::STK_BlockPointer:
3880 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00003881 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00003882 case Type::STK_CPointer:
3883 return CK_BitCast;
3884 case Type::STK_BlockPointer:
3885 return (SrcKind == Type::STK_BlockPointer
3886 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
3887 case Type::STK_ObjCObjectPointer:
3888 if (SrcKind == Type::STK_ObjCObjectPointer)
3889 return CK_BitCast;
3890 else if (SrcKind == Type::STK_CPointer)
3891 return CK_CPointerToObjCPointerCast;
John McCalldc05b112011-09-10 01:16:55 +00003892 else {
3893 maybeExtendBlockObject(S, Src);
John McCall1d9b3b22011-09-09 05:25:32 +00003894 return CK_BlockPointerToObjCPointerCast;
John McCalldc05b112011-09-10 01:16:55 +00003895 }
John McCalldaa8e4e2010-11-15 09:13:47 +00003896 case Type::STK_Bool:
3897 return CK_PointerToBoolean;
3898 case Type::STK_Integral:
3899 return CK_PointerToIntegral;
3900 case Type::STK_Floating:
3901 case Type::STK_FloatingComplex:
3902 case Type::STK_IntegralComplex:
3903 case Type::STK_MemberPointer:
3904 llvm_unreachable("illegal cast from pointer");
3905 }
3906 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003907
John McCalldaa8e4e2010-11-15 09:13:47 +00003908 case Type::STK_Bool: // casting from bool is like casting from an integer
3909 case Type::STK_Integral:
3910 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00003911 case Type::STK_CPointer:
3912 case Type::STK_ObjCObjectPointer:
3913 case Type::STK_BlockPointer:
Richard Trieu67e29332011-08-02 04:35:43 +00003914 if (Src.get()->isNullPointerConstant(S.Context,
3915 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00003916 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00003917 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00003918 case Type::STK_Bool:
3919 return CK_IntegralToBoolean;
3920 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00003921 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003922 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00003923 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00003924 case Type::STK_IntegralComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003925 Src = S.ImpCastExprToType(Src.take(),
3926 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003927 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00003928 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003929 case Type::STK_FloatingComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003930 Src = S.ImpCastExprToType(Src.take(),
3931 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003932 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00003933 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003934 case Type::STK_MemberPointer:
3935 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003936 }
3937 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003938
John McCalldaa8e4e2010-11-15 09:13:47 +00003939 case Type::STK_Floating:
3940 switch (DestTy->getScalarTypeKind()) {
3941 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00003942 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003943 case Type::STK_Bool:
3944 return CK_FloatingToBoolean;
3945 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00003946 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00003947 case Type::STK_FloatingComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003948 Src = S.ImpCastExprToType(Src.take(),
3949 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003950 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00003951 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003952 case Type::STK_IntegralComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003953 Src = S.ImpCastExprToType(Src.take(),
3954 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003955 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00003956 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00003957 case Type::STK_CPointer:
3958 case Type::STK_ObjCObjectPointer:
3959 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00003960 llvm_unreachable("valid float->pointer cast?");
3961 case Type::STK_MemberPointer:
3962 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003963 }
3964 break;
3965
John McCalldaa8e4e2010-11-15 09:13:47 +00003966 case Type::STK_FloatingComplex:
3967 switch (DestTy->getScalarTypeKind()) {
3968 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003969 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003970 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003971 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00003972 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003973 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00003974 if (S.Context.hasSameType(ET, DestTy))
3975 return CK_FloatingComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00003976 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00003977 return CK_FloatingCast;
3978 }
John McCalldaa8e4e2010-11-15 09:13:47 +00003979 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00003980 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00003981 case Type::STK_Integral:
Richard Trieu67e29332011-08-02 04:35:43 +00003982 Src = S.ImpCastExprToType(Src.take(),
3983 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003984 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00003985 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00003986 case Type::STK_CPointer:
3987 case Type::STK_ObjCObjectPointer:
3988 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00003989 llvm_unreachable("valid complex float->pointer cast?");
3990 case Type::STK_MemberPointer:
3991 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003992 }
3993 break;
3994
John McCalldaa8e4e2010-11-15 09:13:47 +00003995 case Type::STK_IntegralComplex:
3996 switch (DestTy->getScalarTypeKind()) {
3997 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003998 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003999 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004000 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004001 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004002 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00004003 if (S.Context.hasSameType(ET, DestTy))
4004 return CK_IntegralComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00004005 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004006 return CK_IntegralCast;
4007 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004008 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004009 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004010 case Type::STK_Floating:
Richard Trieu67e29332011-08-02 04:35:43 +00004011 Src = S.ImpCastExprToType(Src.take(),
4012 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00004013 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004014 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00004015 case Type::STK_CPointer:
4016 case Type::STK_ObjCObjectPointer:
4017 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004018 llvm_unreachable("valid complex int->pointer cast?");
4019 case Type::STK_MemberPointer:
4020 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004021 }
4022 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00004023 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004024
John McCallf3ea8cf2010-11-14 08:17:51 +00004025 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00004026}
4027
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004028/// CheckCastTypes - Check type constraints for casting between types.
Richard Trieuccd891a2011-09-09 01:45:06 +00004029ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc,
4030 SourceRange TypeRange, QualType CastType,
4031 Expr *CastExpr, CastKind &Kind,
4032 ExprValueKind &VK, CXXCastPath &BasePath,
4033 bool FunctionalStyle) {
4034 if (CastExpr->getType() == Context.UnknownAnyTy)
4035 return checkUnknownAnyCast(TypeRange, CastType, CastExpr, Kind, VK,
4036 BasePath);
John McCall1de4d4e2011-04-07 08:22:57 +00004037
Sebastian Redl9cc11e72009-07-25 15:41:38 +00004038 if (getLangOptions().CPlusPlus)
John McCallf85e1932011-06-15 23:02:42 +00004039 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004040 CastExpr->getLocEnd()),
4041 CastType, VK, CastExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004042 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00004043
Richard Trieuccd891a2011-09-09 01:45:06 +00004044 assert(!CastExpr->getType()->isPlaceholderType());
John McCallfb8721c2011-04-10 19:13:55 +00004045
John McCallf89e55a2010-11-18 06:31:45 +00004046 // We only support r-value casts in C.
4047 VK = VK_RValue;
4048
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004049 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4050 // type needs to be scalar.
Richard Trieuccd891a2011-09-09 01:45:06 +00004051 if (CastType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00004052 // We don't necessarily do lvalue-to-rvalue conversions on this.
Richard Trieuccd891a2011-09-09 01:45:06 +00004053 ExprResult castExprRes = IgnoredValueConversions(CastExpr);
John Wiegley429bb272011-04-08 18:41:53 +00004054 if (castExprRes.isInvalid())
4055 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004056 CastExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00004057
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004058 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00004059 Kind = CK_ToVoid;
Richard Trieuccd891a2011-09-09 01:45:06 +00004060 return Owned(CastExpr);
Anders Carlssonebeaf202009-10-16 02:35:04 +00004061 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004062
Richard Trieuccd891a2011-09-09 01:45:06 +00004063 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(CastExpr);
John Wiegley429bb272011-04-08 18:41:53 +00004064 if (castExprRes.isInvalid())
4065 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004066 CastExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00004067
Richard Trieuccd891a2011-09-09 01:45:06 +00004068 if (RequireCompleteType(TypeRange.getBegin(), CastType,
Eli Friedman8d438082010-07-17 20:43:49 +00004069 diag::err_typecheck_cast_to_incomplete))
John Wiegley429bb272011-04-08 18:41:53 +00004070 return ExprError();
Eli Friedman8d438082010-07-17 20:43:49 +00004071
Richard Trieuccd891a2011-09-09 01:45:06 +00004072 if (!CastType->isScalarType() && !CastType->isVectorType()) {
4073 if (Context.hasSameUnqualifiedType(CastType, CastExpr->getType()) &&
4074 (CastType->isStructureType() || CastType->isUnionType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004075 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004076 // FIXME: Check that the cast destination type is complete.
Richard Trieuccd891a2011-09-09 01:45:06 +00004077 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
4078 << CastType << CastExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004079 Kind = CK_NoOp;
Richard Trieuccd891a2011-09-09 01:45:06 +00004080 return Owned(CastExpr);
Anders Carlssonc3516322009-10-16 02:48:28 +00004081 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004082
Richard Trieuccd891a2011-09-09 01:45:06 +00004083 if (CastType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004084 // GCC cast to union extension
Richard Trieuccd891a2011-09-09 01:45:06 +00004085 RecordDecl *RD = CastType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004086 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004087 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004088 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004089 if (Context.hasSameUnqualifiedType(Field->getType(),
Richard Trieuccd891a2011-09-09 01:45:06 +00004090 CastExpr->getType()) &&
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00004091 !Field->isUnnamedBitfield()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00004092 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_to_union)
4093 << CastExpr->getSourceRange();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004094 break;
4095 }
4096 }
John Wiegley429bb272011-04-08 18:41:53 +00004097 if (Field == FieldEnd) {
Richard Trieuccd891a2011-09-09 01:45:06 +00004098 Diag(TypeRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4099 << CastExpr->getType() << CastExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004100 return ExprError();
4101 }
John McCall2de56d12010-08-25 11:45:40 +00004102 Kind = CK_ToUnion;
Richard Trieuccd891a2011-09-09 01:45:06 +00004103 return Owned(CastExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004104 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004105
Anders Carlssonc3516322009-10-16 02:48:28 +00004106 // Reject any other conversions to non-scalar types.
Richard Trieuccd891a2011-09-09 01:45:06 +00004107 Diag(TypeRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
4108 << CastType << CastExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004109 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00004110 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004111
John McCallf3ea8cf2010-11-14 08:17:51 +00004112 // The type we're casting to is known to be a scalar or vector.
4113
4114 // Require the operand to be a scalar or vector.
Richard Trieuccd891a2011-09-09 01:45:06 +00004115 if (!CastExpr->getType()->isScalarType() &&
4116 !CastExpr->getType()->isVectorType()) {
4117 Diag(CastExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004118 diag::err_typecheck_expect_scalar_operand)
Richard Trieuccd891a2011-09-09 01:45:06 +00004119 << CastExpr->getType() << CastExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004120 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00004121 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004122
Richard Trieuccd891a2011-09-09 01:45:06 +00004123 if (CastType->isExtVectorType())
4124 return CheckExtVectorCast(TypeRange, CastType, CastExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004125
Richard Trieuccd891a2011-09-09 01:45:06 +00004126 if (CastType->isVectorType()) {
4127 if (CastType->getAs<VectorType>()->getVectorKind() ==
Anton Yartsevd06fea82011-03-27 09:32:40 +00004128 VectorType::AltiVecVector &&
Richard Trieuccd891a2011-09-09 01:45:06 +00004129 (CastExpr->getType()->isIntegerType() ||
4130 CastExpr->getType()->isFloatingType())) {
Anton Yartsevd06fea82011-03-27 09:32:40 +00004131 Kind = CK_VectorSplat;
Richard Trieuccd891a2011-09-09 01:45:06 +00004132 return Owned(CastExpr);
4133 } else if (CheckVectorCast(TypeRange, CastType, CastExpr->getType(),
4134 Kind)) {
John Wiegley429bb272011-04-08 18:41:53 +00004135 return ExprError();
Anton Yartsevd06fea82011-03-27 09:32:40 +00004136 } else
Richard Trieuccd891a2011-09-09 01:45:06 +00004137 return Owned(CastExpr);
Anton Yartsevd06fea82011-03-27 09:32:40 +00004138 }
Richard Trieuccd891a2011-09-09 01:45:06 +00004139 if (CastExpr->getType()->isVectorType()) {
4140 if (CheckVectorCast(TypeRange, CastExpr->getType(), CastType, Kind))
John Wiegley429bb272011-04-08 18:41:53 +00004141 return ExprError();
4142 else
Richard Trieuccd891a2011-09-09 01:45:06 +00004143 return Owned(CastExpr);
John Wiegley429bb272011-04-08 18:41:53 +00004144 }
Anders Carlssonc3516322009-10-16 02:48:28 +00004145
John McCallf3ea8cf2010-11-14 08:17:51 +00004146 // The source and target types are both scalars, i.e.
4147 // - arithmetic types (fundamental, enum, and complex)
4148 // - all kinds of pointers
4149 // Note that member pointers were filtered out with C++, above.
4150
Richard Trieuccd891a2011-09-09 01:45:06 +00004151 if (isa<ObjCSelectorExpr>(CastExpr)) {
4152 Diag(CastExpr->getLocStart(), diag::err_cast_selector_expr);
John Wiegley429bb272011-04-08 18:41:53 +00004153 return ExprError();
4154 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004155
John McCallf3ea8cf2010-11-14 08:17:51 +00004156 // If either type is a pointer, the other type has to be either an
4157 // integer or a pointer.
Richard Trieuccd891a2011-09-09 01:45:06 +00004158 QualType CastExprType = CastExpr->getType();
4159 if (!CastType->isArithmeticType()) {
4160 if (!CastExprType->isIntegralType(Context) &&
4161 CastExprType->isArithmeticType()) {
4162 Diag(CastExpr->getLocStart(),
John Wiegley429bb272011-04-08 18:41:53 +00004163 diag::err_cast_pointer_from_non_pointer_int)
Richard Trieuccd891a2011-09-09 01:45:06 +00004164 << CastExprType << CastExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004165 return ExprError();
4166 }
Richard Trieuccd891a2011-09-09 01:45:06 +00004167 } else if (!CastExpr->getType()->isArithmeticType()) {
4168 if (!CastType->isIntegralType(Context) && CastType->isArithmeticType()) {
4169 Diag(CastExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
4170 << CastType << CastExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004171 return ExprError();
4172 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004173 }
Anders Carlsson82debc72009-10-18 18:12:03 +00004174
John McCallf85e1932011-06-15 23:02:42 +00004175 if (getLangOptions().ObjCAutoRefCount) {
4176 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
Richard Trieuccd891a2011-09-09 01:45:06 +00004177 CheckObjCARCConversion(SourceRange(CastStartLoc, CastExpr->getLocEnd()),
4178 CastType, CastExpr, CCK_CStyleCast);
John McCallf85e1932011-06-15 23:02:42 +00004179
Richard Trieuccd891a2011-09-09 01:45:06 +00004180 if (const PointerType *CastPtr = CastType->getAs<PointerType>()) {
4181 if (const PointerType *ExprPtr = CastExprType->getAs<PointerType>()) {
John McCallf85e1932011-06-15 23:02:42 +00004182 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4183 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4184 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4185 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4186 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
Richard Trieuccd891a2011-09-09 01:45:06 +00004187 Diag(CastExpr->getLocStart(),
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00004188 diag::err_typecheck_incompatible_ownership)
Richard Trieuccd891a2011-09-09 01:45:06 +00004189 << CastExprType << CastType << AA_Casting
4190 << CastExpr->getSourceRange();
John McCallf85e1932011-06-15 23:02:42 +00004191
4192 return ExprError();
4193 }
4194 }
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00004195 }
Richard Trieuccd891a2011-09-09 01:45:06 +00004196 else if (!CheckObjCARCUnavailableWeakConversion(CastType, CastExprType)) {
4197 Diag(CastExpr->getLocStart(),
Fariborz Jahanian82007c32011-07-08 17:41:42 +00004198 diag::err_arc_convesion_of_weak_unavailable) << 1
Richard Trieuccd891a2011-09-09 01:45:06 +00004199 << CastExprType << CastType
4200 << CastExpr->getSourceRange();
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00004201 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00004202 }
4203 }
4204
Richard Trieuccd891a2011-09-09 01:45:06 +00004205 castExprRes = Owned(CastExpr);
4206 Kind = PrepareScalarCast(*this, castExprRes, CastType);
John Wiegley429bb272011-04-08 18:41:53 +00004207 if (castExprRes.isInvalid())
4208 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004209 CastExpr = castExprRes.take();
John McCallb7f4ffe2010-08-12 21:44:57 +00004210
John McCallf3ea8cf2010-11-14 08:17:51 +00004211 if (Kind == CK_BitCast)
Richard Trieuccd891a2011-09-09 01:45:06 +00004212 CheckCastAlign(CastExpr, CastType, TypeRange);
John McCallb7f4ffe2010-08-12 21:44:57 +00004213
Richard Trieuccd891a2011-09-09 01:45:06 +00004214 return Owned(CastExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004215}
4216
Anders Carlssonc3516322009-10-16 02:48:28 +00004217bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004218 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004219 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004220
Anders Carlssona64db8f2007-11-27 05:51:55 +00004221 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004222 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004223 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004224 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004225 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004226 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004227 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004228 } else
4229 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004230 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004231 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004232
John McCall2de56d12010-08-25 11:45:40 +00004233 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004234 return false;
4235}
4236
John Wiegley429bb272011-04-08 18:41:53 +00004237ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4238 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004239 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004240
Anders Carlsson16a89042009-10-16 05:23:41 +00004241 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004242
Nate Begeman9b10da62009-06-27 22:05:55 +00004243 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4244 // an ExtVectorType.
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004245 // In OpenCL, casts between vectors of different types are not allowed.
4246 // (See OpenCL 6.2).
Nate Begeman58d29a42009-06-26 00:50:28 +00004247 if (SrcTy->isVectorType()) {
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004248 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4249 || (getLangOptions().OpenCL &&
4250 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004251 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004252 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004253 return ExprError();
4254 }
John McCall2de56d12010-08-25 11:45:40 +00004255 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004256 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004257 }
4258
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004259 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004260 // conversion will take place first from scalar to elt type, and then
4261 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004262 if (SrcTy->isPointerType())
4263 return Diag(R.getBegin(),
4264 diag::err_invalid_conversion_between_vector_and_scalar)
4265 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004266
4267 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004268 ExprResult CastExprRes = Owned(CastExpr);
4269 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4270 if (CastExprRes.isInvalid())
4271 return ExprError();
4272 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004273
John McCall2de56d12010-08-25 11:45:40 +00004274 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004275 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004276}
4277
John McCall60d7b3a2010-08-24 06:29:42 +00004278ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004279Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4280 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004281 SourceLocation RParenLoc, Expr *CastExpr) {
4282 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004283 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004284
Richard Trieuccd891a2011-09-09 01:45:06 +00004285 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004286 if (D.isInvalidType())
4287 return ExprError();
4288
4289 if (getLangOptions().CPlusPlus) {
4290 // Check that there are no default arguments (C++ only).
4291 CheckExtraCXXDefaultArguments(D);
4292 }
4293
4294 QualType castType = castTInfo->getType();
4295 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004296
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004297 bool isVectorLiteral = false;
4298
4299 // Check for an altivec or OpenCL literal,
4300 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00004301 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4302 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
Tobias Grosser37c31c22011-09-21 18:28:29 +00004303 if ((getLangOptions().AltiVec || getLangOptions().OpenCL)
4304 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004305 if (PLE && PLE->getNumExprs() == 0) {
4306 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4307 return ExprError();
4308 }
4309 if (PE || PLE->getNumExprs() == 1) {
4310 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4311 if (!E->getType()->isVectorType())
4312 isVectorLiteral = true;
4313 }
4314 else
4315 isVectorLiteral = true;
4316 }
4317
4318 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4319 // then handle it as such.
4320 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00004321 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004322
Nate Begeman2ef13e52009-08-10 23:49:36 +00004323 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004324 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4325 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00004326 if (isa<ParenListExpr>(CastExpr)) {
4327 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004328 if (Result.isInvalid()) return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004329 CastExpr = Result.take();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004330 }
John McCallb042fdf2010-01-15 18:56:44 +00004331
Richard Trieuccd891a2011-09-09 01:45:06 +00004332 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004333}
4334
John McCall60d7b3a2010-08-24 06:29:42 +00004335ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00004336Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004337 SourceLocation RParenLoc, Expr *CastExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004338 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00004339 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00004340 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +00004341 ExprResult CastResult =
John McCallf85e1932011-06-15 23:02:42 +00004342 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
Richard Trieuccd891a2011-09-09 01:45:06 +00004343 CastExpr, Kind, VK, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +00004344 if (CastResult.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004345 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004346 CastExpr = CastResult.take();
Anders Carlsson0aebc812009-09-09 21:33:21 +00004347
Richard Trieu67e29332011-08-02 04:35:43 +00004348 return Owned(CStyleCastExpr::Create(
Richard Trieuccd891a2011-09-09 01:45:06 +00004349 Context, Ty->getType().getNonLValueExprType(Context), VK, Kind, CastExpr,
Richard Trieu67e29332011-08-02 04:35:43 +00004350 &BasePath, Ty, LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00004351}
4352
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004353ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4354 SourceLocation RParenLoc, Expr *E,
4355 TypeSourceInfo *TInfo) {
4356 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4357 "Expected paren or paren list expression");
4358
4359 Expr **exprs;
4360 unsigned numExprs;
4361 Expr *subExpr;
4362 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4363 exprs = PE->getExprs();
4364 numExprs = PE->getNumExprs();
4365 } else {
4366 subExpr = cast<ParenExpr>(E)->getSubExpr();
4367 exprs = &subExpr;
4368 numExprs = 1;
4369 }
4370
4371 QualType Ty = TInfo->getType();
4372 assert(Ty->isVectorType() && "Expected vector type");
4373
Chris Lattner5f9e2722011-07-23 10:55:15 +00004374 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004375 const VectorType *VTy = Ty->getAs<VectorType>();
4376 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4377
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004378 // '(...)' form of vector initialization in AltiVec: the number of
4379 // initializers must be one or must match the size of the vector.
4380 // If a single value is specified in the initializer then it will be
4381 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004382 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004383 // The number of initializers must be one or must match the size of the
4384 // vector. If a single value is specified in the initializer then it will
4385 // be replicated to all the components of the vector
4386 if (numExprs == 1) {
4387 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4388 ExprResult Literal = Owned(exprs[0]);
4389 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4390 PrepareScalarCast(*this, Literal, ElemTy));
4391 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4392 }
4393 else if (numExprs < numElems) {
4394 Diag(E->getExprLoc(),
4395 diag::err_incorrect_number_of_vector_initializers);
4396 return ExprError();
4397 }
4398 else
4399 for (unsigned i = 0, e = numExprs; i != e; ++i)
4400 initExprs.push_back(exprs[i]);
4401 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004402 else {
4403 // For OpenCL, when the number of initializers is a single value,
4404 // it will be replicated to all components of the vector.
4405 if (getLangOptions().OpenCL &&
4406 VTy->getVectorKind() == VectorType::GenericVector &&
4407 numExprs == 1) {
4408 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4409 ExprResult Literal = Owned(exprs[0]);
4410 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4411 PrepareScalarCast(*this, Literal, ElemTy));
4412 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4413 }
4414
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004415 for (unsigned i = 0, e = numExprs; i != e; ++i)
4416 initExprs.push_back(exprs[i]);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004417 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004418 // FIXME: This means that pretty-printing the final AST will produce curly
4419 // braces instead of the original commas.
4420 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4421 &initExprs[0],
4422 initExprs.size(), RParenLoc);
4423 initE->setType(Ty);
4424 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4425}
4426
Nate Begeman2ef13e52009-08-10 23:49:36 +00004427/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4428/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004429ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004430Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4431 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004432 if (!E)
Richard Trieuccd891a2011-09-09 01:45:06 +00004433 return Owned(OrigExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004434
John McCall60d7b3a2010-08-24 06:29:42 +00004435 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004436
Nate Begeman2ef13e52009-08-10 23:49:36 +00004437 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004438 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4439 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004440
John McCall9ae2f072010-08-23 23:25:46 +00004441 if (Result.isInvalid()) return ExprError();
4442
4443 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004444}
4445
John McCall60d7b3a2010-08-24 06:29:42 +00004446ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Richard Trieuccd891a2011-09-09 01:45:06 +00004447 SourceLocation R,
4448 MultiExprArg Val) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004449 unsigned nexprs = Val.size();
4450 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004451 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4452 Expr *expr;
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004453 if (nexprs == 1)
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004454 expr = new (Context) ParenExpr(L, R, exprs[0]);
4455 else
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004456 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4457 exprs[nexprs-1]->getType());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004458 return Owned(expr);
4459}
4460
Chandler Carruth82214a82011-02-18 23:54:50 +00004461/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004462/// constant and the other is not a pointer. Returns true if a diagnostic is
4463/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00004464bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00004465 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004466 Expr *NullExpr = LHSExpr;
4467 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004468 Expr::NullPointerConstantKind NullKind =
4469 NullExpr->isNullPointerConstant(Context,
4470 Expr::NPC_ValueDependentIsNotNull);
4471
4472 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004473 NullExpr = RHSExpr;
4474 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004475 NullKind =
4476 NullExpr->isNullPointerConstant(Context,
4477 Expr::NPC_ValueDependentIsNotNull);
4478 }
4479
4480 if (NullKind == Expr::NPCK_NotNull)
4481 return false;
4482
4483 if (NullKind == Expr::NPCK_ZeroInteger) {
4484 // In this case, check to make sure that we got here from a "NULL"
4485 // string in the source code.
4486 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004487 SourceLocation loc = NullExpr->getExprLoc();
4488 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004489 return false;
4490 }
4491
4492 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4493 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4494 << NonPointerExpr->getType() << DiagType
4495 << NonPointerExpr->getSourceRange();
4496 return true;
4497}
4498
Richard Trieu26f96072011-09-02 01:51:02 +00004499/// \brief Return false if the condition expression is valid, true otherwise.
4500static bool checkCondition(Sema &S, Expr *Cond) {
4501 QualType CondTy = Cond->getType();
4502
4503 // C99 6.5.15p2
4504 if (CondTy->isScalarType()) return false;
4505
4506 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4507 if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4508 return false;
4509
4510 // Emit the proper error message.
4511 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4512 diag::err_typecheck_cond_expect_scalar :
4513 diag::err_typecheck_cond_expect_scalar_or_vector)
4514 << CondTy;
4515 return true;
4516}
4517
4518/// \brief Return false if the two expressions can be converted to a vector,
4519/// true otherwise
4520static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4521 ExprResult &RHS,
4522 QualType CondTy) {
4523 // Both operands should be of scalar type.
4524 if (!LHS.get()->getType()->isScalarType()) {
4525 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4526 << CondTy;
4527 return true;
4528 }
4529 if (!RHS.get()->getType()->isScalarType()) {
4530 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4531 << CondTy;
4532 return true;
4533 }
4534
4535 // Implicity convert these scalars to the type of the condition.
4536 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4537 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4538 return false;
4539}
4540
4541/// \brief Handle when one or both operands are void type.
4542static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4543 ExprResult &RHS) {
4544 Expr *LHSExpr = LHS.get();
4545 Expr *RHSExpr = RHS.get();
4546
4547 if (!LHSExpr->getType()->isVoidType())
4548 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4549 << RHSExpr->getSourceRange();
4550 if (!RHSExpr->getType()->isVoidType())
4551 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4552 << LHSExpr->getSourceRange();
4553 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4554 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4555 return S.Context.VoidTy;
4556}
4557
4558/// \brief Return false if the NullExpr can be promoted to PointerTy,
4559/// true otherwise.
4560static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4561 QualType PointerTy) {
4562 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4563 !NullExpr.get()->isNullPointerConstant(S.Context,
4564 Expr::NPC_ValueDependentIsNull))
4565 return true;
4566
4567 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4568 return false;
4569}
4570
4571/// \brief Checks compatibility between two pointers and return the resulting
4572/// type.
4573static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4574 ExprResult &RHS,
4575 SourceLocation Loc) {
4576 QualType LHSTy = LHS.get()->getType();
4577 QualType RHSTy = RHS.get()->getType();
4578
4579 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4580 // Two identical pointers types are always compatible.
4581 return LHSTy;
4582 }
4583
4584 QualType lhptee, rhptee;
4585
4586 // Get the pointee types.
John McCall1d9b3b22011-09-09 05:25:32 +00004587 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4588 lhptee = LHSBTy->getPointeeType();
4589 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004590 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00004591 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4592 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004593 }
4594
4595 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4596 rhptee.getUnqualifiedType())) {
4597 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4598 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4599 << RHS.get()->getSourceRange();
4600 // In this situation, we assume void* type. No especially good
4601 // reason, but this is what gcc does, and we do have to pick
4602 // to get a consistent AST.
4603 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4604 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4605 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4606 return incompatTy;
4607 }
4608
4609 // The pointer types are compatible.
4610 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4611 // differently qualified versions of compatible types, the result type is
4612 // a pointer to an appropriately qualified version of the *composite*
4613 // type.
4614 // FIXME: Need to calculate the composite type.
4615 // FIXME: Need to add qualifiers
4616
4617 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4618 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4619 return LHSTy;
4620}
4621
4622/// \brief Return the resulting type when the operands are both block pointers.
4623static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4624 ExprResult &LHS,
4625 ExprResult &RHS,
4626 SourceLocation Loc) {
4627 QualType LHSTy = LHS.get()->getType();
4628 QualType RHSTy = RHS.get()->getType();
4629
4630 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4631 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4632 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4633 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4634 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4635 return destType;
4636 }
4637 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4638 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4639 << RHS.get()->getSourceRange();
4640 return QualType();
4641 }
4642
4643 // We have 2 block pointer types.
4644 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4645}
4646
4647/// \brief Return the resulting type when the operands are both pointers.
4648static QualType
4649checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4650 ExprResult &RHS,
4651 SourceLocation Loc) {
4652 // get the pointer types
4653 QualType LHSTy = LHS.get()->getType();
4654 QualType RHSTy = RHS.get()->getType();
4655
4656 // get the "pointed to" types
4657 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4658 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4659
4660 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4661 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4662 // Figure out necessary qualifiers (C99 6.5.15p6)
4663 QualType destPointee
4664 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4665 QualType destType = S.Context.getPointerType(destPointee);
4666 // Add qualifiers if necessary.
4667 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4668 // Promote to void*.
4669 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4670 return destType;
4671 }
4672 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4673 QualType destPointee
4674 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4675 QualType destType = S.Context.getPointerType(destPointee);
4676 // Add qualifiers if necessary.
4677 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4678 // Promote to void*.
4679 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4680 return destType;
4681 }
4682
4683 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4684}
4685
4686/// \brief Return false if the first expression is not an integer and the second
4687/// expression is not a pointer, true otherwise.
4688static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4689 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004690 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00004691 if (!PointerExpr->getType()->isPointerType() ||
4692 !Int.get()->getType()->isIntegerType())
4693 return false;
4694
Richard Trieuccd891a2011-09-09 01:45:06 +00004695 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4696 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00004697
4698 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4699 << Expr1->getType() << Expr2->getType()
4700 << Expr1->getSourceRange() << Expr2->getSourceRange();
4701 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4702 CK_IntegralToPointer);
4703 return true;
4704}
4705
Richard Trieu33fc7572011-09-06 20:06:39 +00004706/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4707/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004708/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004709QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4710 ExprResult &RHS, ExprValueKind &VK,
4711 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004712 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004713
Richard Trieu33fc7572011-09-06 20:06:39 +00004714 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4715 if (!LHSResult.isUsable()) return QualType();
4716 LHS = move(LHSResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004717
Richard Trieu33fc7572011-09-06 20:06:39 +00004718 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4719 if (!RHSResult.isUsable()) return QualType();
4720 RHS = move(RHSResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004721
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004722 // C++ is sufficiently different to merit its own checker.
4723 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004724 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004725
4726 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004727 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004728
John Wiegley429bb272011-04-08 18:41:53 +00004729 Cond = UsualUnaryConversions(Cond.take());
4730 if (Cond.isInvalid())
4731 return QualType();
4732 LHS = UsualUnaryConversions(LHS.take());
4733 if (LHS.isInvalid())
4734 return QualType();
4735 RHS = UsualUnaryConversions(RHS.take());
4736 if (RHS.isInvalid())
4737 return QualType();
4738
4739 QualType CondTy = Cond.get()->getType();
4740 QualType LHSTy = LHS.get()->getType();
4741 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004742
Reid Spencer5f016e22007-07-11 17:01:13 +00004743 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00004744 if (checkCondition(*this, Cond.get()))
4745 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004746
Chris Lattner70d67a92008-01-06 22:42:25 +00004747 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004748 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004749 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004750
Nate Begeman6155d732010-09-20 22:41:17 +00004751 // OpenCL: If the condition is a vector, and both operands are scalar,
4752 // attempt to implicity convert them to the vector type to act like the
4753 // built in select.
Richard Trieu26f96072011-09-02 01:51:02 +00004754 if (getLangOptions().OpenCL && CondTy->isVectorType())
4755 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00004756 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00004757
Chris Lattner70d67a92008-01-06 22:42:25 +00004758 // If both operands have arithmetic type, do the usual arithmetic conversions
4759 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004760 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4761 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004762 if (LHS.isInvalid() || RHS.isInvalid())
4763 return QualType();
4764 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004765 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004766
Chris Lattner70d67a92008-01-06 22:42:25 +00004767 // If both operands are the same structure or union type, the result is that
4768 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004769 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4770 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004771 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004772 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004773 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004774 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004775 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004776 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004777
Chris Lattner70d67a92008-01-06 22:42:25 +00004778 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004779 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004780 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004781 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00004782 }
Richard Trieu26f96072011-09-02 01:51:02 +00004783
Steve Naroffb6d54e52008-01-08 01:11:38 +00004784 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4785 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00004786 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4787 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004788
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004789 // All objective-c pointer type analysis is done here.
4790 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4791 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00004792 if (LHS.isInvalid() || RHS.isInvalid())
4793 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004794 if (!compositeType.isNull())
4795 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004796
4797
Steve Naroff7154a772009-07-01 14:36:47 +00004798 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00004799 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4800 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4801 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004802
Steve Naroff7154a772009-07-01 14:36:47 +00004803 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00004804 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4805 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4806 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004807
John McCall404cd162010-11-13 01:35:44 +00004808 // GCC compatibility: soften pointer/integer mismatch. Note that
4809 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00004810 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4811 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00004812 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004813 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4814 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00004815 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004816
Chandler Carruth82214a82011-02-18 23:54:50 +00004817 // Emit a better diagnostic if one of the expressions is a null pointer
4818 // constant and the other is not a pointer type. In this case, the user most
4819 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00004820 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00004821 return QualType();
4822
Chris Lattner70d67a92008-01-06 22:42:25 +00004823 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004824 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00004825 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4826 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004827 return QualType();
4828}
4829
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004830/// FindCompositeObjCPointerType - Helper method to find composite type of
4831/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00004832QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00004833 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00004834 QualType LHSTy = LHS.get()->getType();
4835 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004836
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004837 // Handle things like Class and struct objc_class*. Here we case the result
4838 // to the pseudo-builtin, because that will be implicitly cast back to the
4839 // redefinition type if an attempt is made to access its fields.
4840 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004841 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004842 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004843 return LHSTy;
4844 }
4845 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004846 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004847 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004848 return RHSTy;
4849 }
4850 // And the same for struct objc_object* / id
4851 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004852 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004853 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004854 return LHSTy;
4855 }
4856 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004857 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004858 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004859 return RHSTy;
4860 }
4861 // And the same for struct objc_selector* / SEL
4862 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004863 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004864 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004865 return LHSTy;
4866 }
4867 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004868 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004869 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004870 return RHSTy;
4871 }
4872 // Check constraints for Objective-C object pointers types.
4873 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004874
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004875 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4876 // Two identical object pointer types are always compatible.
4877 return LHSTy;
4878 }
John McCall1d9b3b22011-09-09 05:25:32 +00004879 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4880 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004881 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004882
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004883 // If both operands are interfaces and either operand can be
4884 // assigned to the other, use that type as the composite
4885 // type. This allows
4886 // xxx ? (A*) a : (B*) b
4887 // where B is a subclass of A.
4888 //
4889 // Additionally, as for assignment, if either type is 'id'
4890 // allow silent coercion. Finally, if the types are
4891 // incompatible then make sure to use 'id' as the composite
4892 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004893
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004894 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4895 // It could return the composite type.
4896 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4897 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4898 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4899 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4900 } else if ((LHSTy->isObjCQualifiedIdType() ||
4901 RHSTy->isObjCQualifiedIdType()) &&
4902 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4903 // Need to handle "id<xx>" explicitly.
4904 // GCC allows qualified id and any Objective-C type to devolve to
4905 // id. Currently localizing to here until clear this should be
4906 // part of ObjCQualifiedIdTypesAreCompatible.
4907 compositeType = Context.getObjCIdType();
4908 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4909 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004910 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004911 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4912 ;
4913 else {
4914 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4915 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00004916 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004917 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00004918 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4919 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004920 return incompatTy;
4921 }
4922 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00004923 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4924 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004925 return compositeType;
4926 }
4927 // Check Objective-C object pointer types and 'void *'
4928 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4929 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4930 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4931 QualType destPointee
4932 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4933 QualType destType = Context.getPointerType(destPointee);
4934 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004935 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004936 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004937 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004938 return destType;
4939 }
4940 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4941 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4942 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4943 QualType destPointee
4944 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4945 QualType destType = Context.getPointerType(destPointee);
4946 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004947 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004948 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004949 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004950 return destType;
4951 }
4952 return QualType();
4953}
4954
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004955/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004956/// ParenRange in parentheses.
4957static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004958 const PartialDiagnostic &Note,
4959 SourceRange ParenRange) {
4960 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4961 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4962 EndLoc.isValid()) {
4963 Self.Diag(Loc, Note)
4964 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4965 << FixItHint::CreateInsertion(EndLoc, ")");
4966 } else {
4967 // We can't display the parentheses, so just show the bare note.
4968 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004969 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004970}
4971
4972static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4973 return Opc >= BO_Mul && Opc <= BO_Shr;
4974}
4975
Hans Wennborg2f072b42011-06-09 17:06:51 +00004976/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4977/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00004978/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
4979/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00004980static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00004981 Expr **RHSExprs) {
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00004982 // Don't strip parenthesis: we should not warn if E is in parenthesis.
4983 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00004984 E = E->IgnoreConversionOperator();
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00004985 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00004986
4987 // Built-in binary operator.
4988 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4989 if (IsArithmeticOp(OP->getOpcode())) {
4990 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00004991 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00004992 return true;
4993 }
4994 }
4995
4996 // Overloaded operator.
4997 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4998 if (Call->getNumArgs() != 2)
4999 return false;
5000
5001 // Make sure this is really a binary operator that is safe to pass into
5002 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5003 OverloadedOperatorKind OO = Call->getOperator();
5004 if (OO < OO_Plus || OO > OO_Arrow)
5005 return false;
5006
5007 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5008 if (IsArithmeticOp(OpKind)) {
5009 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00005010 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00005011 return true;
5012 }
5013 }
5014
5015 return false;
5016}
5017
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005018static bool IsLogicOp(BinaryOperatorKind Opc) {
5019 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5020}
5021
Hans Wennborg2f072b42011-06-09 17:06:51 +00005022/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5023/// or is a logical expression such as (x==y) which has int type, but is
5024/// commonly interpreted as boolean.
5025static bool ExprLooksBoolean(Expr *E) {
5026 E = E->IgnoreParenImpCasts();
5027
5028 if (E->getType()->isBooleanType())
5029 return true;
5030 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5031 return IsLogicOp(OP->getOpcode());
5032 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5033 return OP->getOpcode() == UO_LNot;
5034
5035 return false;
5036}
5037
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005038/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5039/// and binary operator are mixed in a way that suggests the programmer assumed
5040/// the conditional operator has higher precedence, for example:
5041/// "int x = a + someBinaryCondition ? 1 : 2".
5042static void DiagnoseConditionalPrecedence(Sema &Self,
5043 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005044 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00005045 Expr *LHSExpr,
5046 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00005047 BinaryOperatorKind CondOpcode;
5048 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005049
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005050 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00005051 return;
5052 if (!ExprLooksBoolean(CondRHS))
5053 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005054
Hans Wennborg2f072b42011-06-09 17:06:51 +00005055 // The condition is an arithmetic binary expression, with a right-
5056 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005057
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005058 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005059 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00005060 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005061
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005062 SuggestParentheses(Self, OpLoc,
5063 Self.PDiag(diag::note_precedence_conditional_silence)
5064 << BinaryOperator::getOpcodeStr(CondOpcode),
5065 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00005066
5067 SuggestParentheses(Self, OpLoc,
5068 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00005069 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005070}
5071
Steve Narofff69936d2007-09-16 03:34:24 +00005072/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005073/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005074ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005075 SourceLocation ColonLoc,
5076 Expr *CondExpr, Expr *LHSExpr,
5077 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005078 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5079 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005080 OpaqueValueExpr *opaqueValue = 0;
5081 Expr *commonExpr = 0;
5082 if (LHSExpr == 0) {
5083 commonExpr = CondExpr;
5084
5085 // We usually want to apply unary conversions *before* saving, except
5086 // in the special case of a C++ l-value conditional.
5087 if (!(getLangOptions().CPlusPlus
5088 && !commonExpr->isTypeDependent()
5089 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5090 && commonExpr->isGLValue()
5091 && commonExpr->isOrdinaryOrBitFieldObject()
5092 && RHSExpr->isOrdinaryOrBitFieldObject()
5093 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005094 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5095 if (commonRes.isInvalid())
5096 return ExprError();
5097 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005098 }
5099
5100 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5101 commonExpr->getType(),
5102 commonExpr->getValueKind(),
5103 commonExpr->getObjectKind());
5104 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005105 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005106
John McCallf89e55a2010-11-18 06:31:45 +00005107 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005108 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005109 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5110 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005111 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005112 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5113 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005114 return ExprError();
5115
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005116 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5117 RHS.get());
5118
John McCall56ca35d2011-02-17 10:25:35 +00005119 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005120 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5121 LHS.take(), ColonLoc,
5122 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005123
5124 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005125 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005126 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5127 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005128}
5129
John McCalle4be87e2011-01-31 23:13:11 +00005130// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005131// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005132// routine is it effectively iqnores the qualifiers on the top level pointee.
5133// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5134// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005135static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005136checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5137 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5138 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005139
Reid Spencer5f016e22007-07-11 17:01:13 +00005140 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005141 const Type *lhptee, *rhptee;
5142 Qualifiers lhq, rhq;
Richard Trieu1da27a12011-09-06 20:21:22 +00005143 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5144 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005145
John McCalle4be87e2011-01-31 23:13:11 +00005146 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005147
5148 // C99 6.5.16.1p1: This following citation is common to constraints
5149 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5150 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005151 Qualifiers lq;
5152
John McCallf85e1932011-06-15 23:02:42 +00005153 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5154 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5155 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5156 // Ignore lifetime for further calculation.
5157 lhq.removeObjCLifetime();
5158 rhq.removeObjCLifetime();
5159 }
5160
John McCall86c05f32011-02-01 00:10:29 +00005161 if (!lhq.compatiblyIncludes(rhq)) {
5162 // Treat address-space mismatches as fatal. TODO: address subspaces
5163 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5164 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5165
John McCallf85e1932011-06-15 23:02:42 +00005166 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005167 // and from void*.
John McCallf85e1932011-06-15 23:02:42 +00005168 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5169 .compatiblyIncludes(
5170 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall22348732011-03-26 02:56:45 +00005171 && (lhptee->isVoidType() || rhptee->isVoidType()))
5172 ; // keep old
5173
John McCallf85e1932011-06-15 23:02:42 +00005174 // Treat lifetime mismatches as fatal.
5175 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5176 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5177
John McCall86c05f32011-02-01 00:10:29 +00005178 // For GCC compatibility, other qualifier mismatches are treated
5179 // as still compatible in C.
5180 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5181 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005182
Mike Stumpeed9cac2009-02-19 03:04:26 +00005183 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5184 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005185 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005186 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005187 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005188 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005189
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005190 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005191 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005192 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005193 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005194
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005195 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005196 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005197 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005198
5199 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005200 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005201 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005202 }
John McCall86c05f32011-02-01 00:10:29 +00005203
Mike Stumpeed9cac2009-02-19 03:04:26 +00005204 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005205 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005206 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5207 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005208 // Check if the pointee types are compatible ignoring the sign.
5209 // We explicitly check for char so that we catch "char" vs
5210 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005211 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005212 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005213 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005214 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005215
Chris Lattner6a2b9262009-10-17 20:33:28 +00005216 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005217 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005218 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005219 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005220
John McCall86c05f32011-02-01 00:10:29 +00005221 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005222 // Types are compatible ignoring the sign. Qualifier incompatibility
5223 // takes priority over sign incompatibility because the sign
5224 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005225 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005226 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005227
John McCalle4be87e2011-01-31 23:13:11 +00005228 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005229 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005230
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005231 // If we are a multi-level pointer, it's possible that our issue is simply
5232 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5233 // the eventual target type is the same and the pointers have the same
5234 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005235 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005236 do {
John McCall86c05f32011-02-01 00:10:29 +00005237 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5238 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005239 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005240
John McCall86c05f32011-02-01 00:10:29 +00005241 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005242 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005243 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005244
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005245 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005246 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005247 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005248 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005249}
5250
John McCalle4be87e2011-01-31 23:13:11 +00005251/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005252/// block pointer types are compatible or whether a block and normal pointer
5253/// are compatible. It is more restrict than comparing two function pointer
5254// types.
John McCalle4be87e2011-01-31 23:13:11 +00005255static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005256checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5257 QualType RHSType) {
5258 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5259 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005260
Steve Naroff1c7d0672008-09-04 15:10:53 +00005261 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005262
Steve Naroff1c7d0672008-09-04 15:10:53 +00005263 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00005264 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5265 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005266
John McCalle4be87e2011-01-31 23:13:11 +00005267 // In C++, the types have to match exactly.
5268 if (S.getLangOptions().CPlusPlus)
5269 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005270
John McCalle4be87e2011-01-31 23:13:11 +00005271 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005272
Steve Naroff1c7d0672008-09-04 15:10:53 +00005273 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005274 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5275 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005276
Richard Trieu1da27a12011-09-06 20:21:22 +00005277 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005278 return Sema::IncompatibleBlockPointer;
5279
Steve Naroff1c7d0672008-09-04 15:10:53 +00005280 return ConvTy;
5281}
5282
John McCalle4be87e2011-01-31 23:13:11 +00005283/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005284/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005285static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005286checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5287 QualType RHSType) {
5288 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5289 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005290
Richard Trieu1da27a12011-09-06 20:21:22 +00005291 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005292 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005293 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5294 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005295 return Sema::IncompatiblePointer;
5296 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005297 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005298 if (RHSType->isObjCBuiltinType()) {
Richard Trieu1da27a12011-09-06 20:21:22 +00005299 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5300 !LHSType->isObjCQualifiedClassType())
Fariborz Jahanian412a4962011-09-15 20:40:18 +00005301 return Sema::IncompatiblePointer;
John McCalle4be87e2011-01-31 23:13:11 +00005302 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005303 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005304 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5305 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005306
John McCalle4be87e2011-01-31 23:13:11 +00005307 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5308 return Sema::CompatiblePointerDiscardsQualifiers;
5309
Richard Trieu1da27a12011-09-06 20:21:22 +00005310 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005311 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00005312 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005313 return Sema::IncompatibleObjCQualifiedId;
5314 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005315}
5316
John McCall1c23e912010-11-16 02:32:08 +00005317Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005318Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00005319 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00005320 // Fake up an opaque expression. We don't actually care about what
5321 // cast operations are required, so if CheckAssignmentConstraints
5322 // adds casts to this they'll be wasted, but fortunately that doesn't
5323 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00005324 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5325 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00005326 CastKind K = CK_Invalid;
5327
Richard Trieu1da27a12011-09-06 20:21:22 +00005328 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00005329}
5330
Mike Stumpeed9cac2009-02-19 03:04:26 +00005331/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5332/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005333/// pointers. Here are some objectionable examples that GCC considers warnings:
5334///
5335/// int a, *pint;
5336/// short *pshort;
5337/// struct foo *pfoo;
5338///
5339/// pint = pshort; // warning: assignment from incompatible pointer type
5340/// a = pint; // warning: assignment makes integer from pointer without a cast
5341/// pint = a; // warning: assignment makes pointer from integer without a cast
5342/// pint = pfoo; // warning: assignment from incompatible pointer type
5343///
5344/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005345/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005346///
John McCalldaa8e4e2010-11-15 09:13:47 +00005347/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005348Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00005349Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00005350 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00005351 QualType RHSType = RHS.get()->getType();
5352 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00005353
Chris Lattnerfc144e22008-01-04 23:18:45 +00005354 // Get canonical types. We're not formatting these types, just comparing
5355 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00005356 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5357 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005358
John McCallb6cfa242011-01-31 22:28:28 +00005359 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00005360 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005361 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005362 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005363 }
5364
Douglas Gregor9d293df2008-10-28 00:22:11 +00005365 // If the left-hand side is a reference type, then we are in a
5366 // (rare!) case where we've allowed the use of references in C,
5367 // e.g., as a parameter type in a built-in function. In this case,
5368 // just make sure that the type referenced is compatible with the
5369 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00005370 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00005371 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005372 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5373 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005374 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005375 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005376 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005377 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005378 }
John McCallb6cfa242011-01-31 22:28:28 +00005379
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005380 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5381 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005382 if (LHSType->isExtVectorType()) {
5383 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005384 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00005385 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005386 // CK_VectorSplat does T -> vector T, so first cast to the
5387 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005388 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5389 if (elType != RHSType) {
5390 Kind = PrepareScalarCast(*this, RHS, elType);
5391 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005392 }
5393 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005394 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005395 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005396 }
Mike Stump1eb44332009-09-09 15:08:12 +00005397
John McCallb6cfa242011-01-31 22:28:28 +00005398 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005399 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5400 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005401 // Allow assignments of an AltiVec vector type to an equivalent GCC
5402 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00005403 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005404 Kind = CK_BitCast;
5405 return Compatible;
5406 }
5407
Douglas Gregor255210e2010-08-06 10:14:59 +00005408 // If we are allowing lax vector conversions, and LHS and RHS are both
5409 // vectors, the total size only needs to be the same. This is a bitcast;
5410 // no bits are changed but the result type is different.
5411 if (getLangOptions().LaxVectorConversions &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005412 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005413 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005414 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005415 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005416 }
5417 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005418 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005419
John McCallb6cfa242011-01-31 22:28:28 +00005420 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00005421 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5422 !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
5423 Kind = PrepareScalarCast(*this, RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005424 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005425 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005426
John McCallb6cfa242011-01-31 22:28:28 +00005427 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005428 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005429 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005430 if (isa<PointerType>(RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005431 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005432 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005433 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005434
John McCallb6cfa242011-01-31 22:28:28 +00005435 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005436 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005437 Kind = CK_IntegralToPointer; // FIXME: null?
5438 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005439 }
John McCallb6cfa242011-01-31 22:28:28 +00005440
5441 // C pointers are not compatible with ObjC object pointers,
5442 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005443 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005444 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005445 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005446 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00005447 return Compatible;
5448 }
5449
5450 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005451 if (RHSType->isObjCClassType() &&
5452 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005453 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005454 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005455 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005456 }
Douglas Gregorc737acb2011-09-27 16:10:05 +00005457
John McCallb6cfa242011-01-31 22:28:28 +00005458 Kind = CK_BitCast;
5459 return IncompatiblePointer;
5460 }
5461
5462 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005463 if (RHSType->getAs<BlockPointerType>()) {
5464 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005465 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005466 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005467 }
Steve Naroffb4406862008-09-29 18:10:17 +00005468 }
John McCallb6cfa242011-01-31 22:28:28 +00005469
Steve Naroff1c7d0672008-09-04 15:10:53 +00005470 return Incompatible;
5471 }
5472
John McCallb6cfa242011-01-31 22:28:28 +00005473 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005474 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005475 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005476 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005477 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005478 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00005479 }
5480
5481 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005482 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005483 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005484 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005485 }
5486
John McCallb6cfa242011-01-31 22:28:28 +00005487 // id -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005488 if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005489 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005490 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005491 }
Steve Naroffb4406862008-09-29 18:10:17 +00005492
John McCallb6cfa242011-01-31 22:28:28 +00005493 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005494 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005495 if (RHSPT->getPointeeType()->isVoidType()) {
5496 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005497 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005498 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005499
Chris Lattnerfc144e22008-01-04 23:18:45 +00005500 return Incompatible;
5501 }
5502
John McCallb6cfa242011-01-31 22:28:28 +00005503 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005504 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005505 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00005506 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005507 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005508 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00005509 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005510 if (getLangOptions().ObjCAutoRefCount &&
5511 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005512 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005513 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005514 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005515 }
5516
5517 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005518 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005519 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005520 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005521 }
5522
John McCallb6cfa242011-01-31 22:28:28 +00005523 // In general, C pointers are not compatible with ObjC object pointers,
5524 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005525 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00005526 Kind = CK_CPointerToObjCPointerCast;
5527
John McCallb6cfa242011-01-31 22:28:28 +00005528 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00005529 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005530 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005531 }
5532
5533 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005534 if (LHSType->isObjCClassType() &&
5535 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005536 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005537 return Compatible;
5538 }
5539
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005540 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005541 }
John McCallb6cfa242011-01-31 22:28:28 +00005542
5543 // T^ -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005544 if (RHSType->isBlockPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00005545 maybeExtendBlockObject(*this, RHS);
John McCall1d9b3b22011-09-09 05:25:32 +00005546 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005547 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005548 }
5549
Steve Naroff14108da2009-07-10 23:34:53 +00005550 return Incompatible;
5551 }
John McCallb6cfa242011-01-31 22:28:28 +00005552
5553 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005554 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005555 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005556 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005557 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005558 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005559 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005560
John McCallb6cfa242011-01-31 22:28:28 +00005561 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005562 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005563 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005564 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005565 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005566
Chris Lattnerfc144e22008-01-04 23:18:45 +00005567 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005568 }
John McCallb6cfa242011-01-31 22:28:28 +00005569
5570 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005571 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005572 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005573 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005574 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005575 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005576 }
Steve Naroff14108da2009-07-10 23:34:53 +00005577
John McCallb6cfa242011-01-31 22:28:28 +00005578 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005579 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005580 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005581 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005582 }
5583
Steve Naroff14108da2009-07-10 23:34:53 +00005584 return Incompatible;
5585 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005586
John McCallb6cfa242011-01-31 22:28:28 +00005587 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00005588 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5589 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005590 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005591 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005592 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005593 }
John McCallb6cfa242011-01-31 22:28:28 +00005594
Reid Spencer5f016e22007-07-11 17:01:13 +00005595 return Incompatible;
5596}
5597
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005598/// \brief Constructs a transparent union from an expression that is
5599/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005600static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5601 ExprResult &EResult, QualType UnionType,
5602 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005603 // Build an initializer list that designates the appropriate member
5604 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005605 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005606 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00005607 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005608 SourceLocation());
5609 Initializer->setType(UnionType);
5610 Initializer->setInitializedFieldInUnion(Field);
5611
5612 // Build a compound literal constructing a value of the transparent
5613 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005614 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005615 EResult = S.Owned(
5616 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5617 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005618}
5619
5620Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005621Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00005622 ExprResult &RHS) {
5623 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005624
Mike Stump1eb44332009-09-09 15:08:12 +00005625 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005626 // transparent_union GCC extension.
5627 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005628 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005629 return Incompatible;
5630
5631 // The field to initialize within the transparent union.
5632 RecordDecl *UD = UT->getDecl();
5633 FieldDecl *InitField = 0;
5634 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005635 for (RecordDecl::field_iterator it = UD->field_begin(),
5636 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005637 it != itend; ++it) {
5638 if (it->getType()->isPointerType()) {
5639 // If the transparent union contains a pointer type, we allow:
5640 // 1) void pointer
5641 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00005642 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00005643 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005644 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005645 InitField = *it;
5646 break;
5647 }
Mike Stump1eb44332009-09-09 15:08:12 +00005648
Richard Trieuf7720da2011-09-06 20:40:12 +00005649 if (RHS.get()->isNullPointerConstant(Context,
5650 Expr::NPC_ValueDependentIsNull)) {
5651 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5652 CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005653 InitField = *it;
5654 break;
5655 }
5656 }
5657
John McCalldaa8e4e2010-11-15 09:13:47 +00005658 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00005659 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005660 == Compatible) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005661 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005662 InitField = *it;
5663 break;
5664 }
5665 }
5666
5667 if (!InitField)
5668 return Incompatible;
5669
Richard Trieuf7720da2011-09-06 20:40:12 +00005670 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005671 return Compatible;
5672}
5673
Chris Lattner5cf216b2008-01-04 18:04:52 +00005674Sema::AssignConvertType
Sebastian Redl14b0c192011-09-24 17:48:00 +00005675Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5676 bool Diagnose) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005677 if (getLangOptions().CPlusPlus) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005678 if (!LHSType->isRecordType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005679 // C++ 5.17p3: If the left operand is not of class type, the
5680 // expression is implicitly converted (C++ 4) to the
5681 // cv-unqualified type of the left operand.
Richard Trieuf7720da2011-09-06 20:40:12 +00005682 ExprResult Res = PerformImplicitConversion(RHS.get(),
5683 LHSType.getUnqualifiedType(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00005684 AA_Assigning, Diagnose);
John Wiegley429bb272011-04-08 18:41:53 +00005685 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005686 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005687 Sema::AssignConvertType result = Compatible;
5688 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00005689 !CheckObjCARCUnavailableWeakConversion(LHSType,
5690 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005691 result = IncompatibleObjCWeakRef;
Richard Trieuf7720da2011-09-06 20:40:12 +00005692 RHS = move(Res);
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005693 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005694 }
5695
5696 // FIXME: Currently, we fall through and treat C++ classes like C
5697 // structures.
Sebastian Redl14b0c192011-09-24 17:48:00 +00005698 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005699
Steve Naroff529a4ad2007-11-27 17:58:44 +00005700 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5701 // a null pointer constant.
Richard Trieuf7720da2011-09-06 20:40:12 +00005702 if ((LHSType->isPointerType() ||
5703 LHSType->isObjCObjectPointerType() ||
5704 LHSType->isBlockPointerType())
5705 && RHS.get()->isNullPointerConstant(Context,
5706 Expr::NPC_ValueDependentIsNull)) {
5707 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005708 return Compatible;
5709 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005710
Chris Lattner943140e2007-10-16 02:55:40 +00005711 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005712 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005713 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005714 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005715 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005716 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00005717 if (!LHSType->isReferenceType()) {
5718 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5719 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005720 return Incompatible;
5721 }
Steve Narofff1120de2007-08-24 22:33:52 +00005722
John McCalldaa8e4e2010-11-15 09:13:47 +00005723 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005724 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00005725 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005726
Steve Narofff1120de2007-08-24 22:33:52 +00005727 // C99 6.5.16.1p2: The value of the right operand is converted to the
5728 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00005729 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5730 // so that we can use references in built-in functions even in C.
5731 // The getNonReferenceType() call makes sure that the resulting expression
5732 // does not have reference type.
Richard Trieuf7720da2011-09-06 20:40:12 +00005733 if (result != Incompatible && RHS.get()->getType() != LHSType)
5734 RHS = ImpCastExprToType(RHS.take(),
5735 LHSType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00005736 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00005737}
5738
Richard Trieuf7720da2011-09-06 20:40:12 +00005739QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5740 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005741 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00005742 << LHS.get()->getType() << RHS.get()->getType()
5743 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00005744 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005745}
5746
Richard Trieu08062aa2011-09-06 21:01:04 +00005747QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00005748 SourceLocation Loc, bool IsCompAssign) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00005749 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005750 // For example, "const float" and "float" are equivalent.
Richard Trieu08062aa2011-09-06 21:01:04 +00005751 QualType LHSType =
5752 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5753 QualType RHSType =
5754 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005755
Nate Begemanbe2341d2008-07-14 18:02:46 +00005756 // If the vector types are identical, return.
Richard Trieu08062aa2011-09-06 21:01:04 +00005757 if (LHSType == RHSType)
5758 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00005759
Douglas Gregor255210e2010-08-06 10:14:59 +00005760 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu08062aa2011-09-06 21:01:04 +00005761 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5762 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5763 if (LHSType->isExtVectorType()) {
5764 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5765 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005766 }
5767
Richard Trieuccd891a2011-09-09 01:45:06 +00005768 if (!IsCompAssign)
Richard Trieu08062aa2011-09-06 21:01:04 +00005769 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5770 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00005771 }
5772
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005773 if (getLangOptions().LaxVectorConversions &&
Richard Trieu08062aa2011-09-06 21:01:04 +00005774 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005775 // If we are allowing lax vector conversions, and LHS and RHS are both
5776 // vectors, the total size only needs to be the same. This is a
5777 // bitcast; no bits are changed but the result type is different.
5778 // FIXME: Should we really be allowing this?
Richard Trieu08062aa2011-09-06 21:01:04 +00005779 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5780 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005781 }
5782
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005783 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5784 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5785 bool swapped = false;
Richard Trieuccd891a2011-09-09 01:45:06 +00005786 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005787 swapped = true;
Richard Trieu08062aa2011-09-06 21:01:04 +00005788 std::swap(RHS, LHS);
5789 std::swap(RHSType, LHSType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005790 }
Mike Stump1eb44332009-09-09 15:08:12 +00005791
Nate Begemandde25982009-06-28 19:12:57 +00005792 // Handle the case of an ext vector and scalar.
Richard Trieu08062aa2011-09-06 21:01:04 +00005793 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005794 QualType EltTy = LV->getElementType();
Richard Trieu08062aa2011-09-06 21:01:04 +00005795 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5796 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005797 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00005798 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005799 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00005800 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5801 if (swapped) std::swap(RHS, LHS);
5802 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005803 }
5804 }
Richard Trieu08062aa2011-09-06 21:01:04 +00005805 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5806 RHSType->isRealFloatingType()) {
5807 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005808 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00005809 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005810 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00005811 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5812 if (swapped) std::swap(RHS, LHS);
5813 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005814 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00005815 }
5816 }
Mike Stump1eb44332009-09-09 15:08:12 +00005817
Nate Begemandde25982009-06-28 19:12:57 +00005818 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu08062aa2011-09-06 21:01:04 +00005819 if (swapped) std::swap(RHS, LHS);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005820 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu08062aa2011-09-06 21:01:04 +00005821 << LHS.get()->getType() << RHS.get()->getType()
5822 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005823 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00005824}
5825
Richard Trieu481037f2011-09-16 00:53:10 +00005826// checkArithmeticNull - Detect when a NULL constant is used improperly in an
5827// expression. These are mainly cases where the null pointer is used as an
5828// integer instead of a pointer.
5829static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5830 SourceLocation Loc, bool IsCompare) {
5831 // The canonical way to check for a GNU null is with isNullPointerConstant,
5832 // but we use a bit of a hack here for speed; this is a relatively
5833 // hot path, and isNullPointerConstant is slow.
5834 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5835 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5836
5837 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5838
5839 // Avoid analyzing cases where the result will either be invalid (and
5840 // diagnosed as such) or entirely valid and not something to warn about.
5841 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5842 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5843 return;
5844
5845 // Comparison operations would not make sense with a null pointer no matter
5846 // what the other expression is.
5847 if (!IsCompare) {
5848 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5849 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5850 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5851 return;
5852 }
5853
5854 // The rest of the operations only make sense with a null pointer
5855 // if the other expression is a pointer.
5856 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5857 NonNullType->canDecayToPointerType())
5858 return;
5859
5860 S.Diag(Loc, diag::warn_null_in_comparison_operation)
5861 << LHSNull /* LHS is NULL */ << NonNullType
5862 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5863}
5864
Richard Trieu08062aa2011-09-06 21:01:04 +00005865QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00005866 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00005867 bool IsCompAssign, bool IsDiv) {
Richard Trieu481037f2011-09-16 00:53:10 +00005868 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5869
Richard Trieu08062aa2011-09-06 21:01:04 +00005870 if (LHS.get()->getType()->isVectorType() ||
5871 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00005872 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005873
Richard Trieuccd891a2011-09-09 01:45:06 +00005874 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00005875 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005876 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005877
Richard Trieu08062aa2011-09-06 21:01:04 +00005878 if (!LHS.get()->getType()->isArithmeticType() ||
5879 !RHS.get()->getType()->isArithmeticType())
5880 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005881
Chris Lattner7ef655a2010-01-12 21:23:57 +00005882 // Check for division by zero.
Richard Trieuccd891a2011-09-09 01:45:06 +00005883 if (IsDiv &&
Richard Trieu08062aa2011-09-06 21:01:04 +00005884 RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00005885 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00005886 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5887 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005888
Chris Lattner7ef655a2010-01-12 21:23:57 +00005889 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005890}
5891
Chris Lattner7ef655a2010-01-12 21:23:57 +00005892QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00005893 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00005894 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5895
Richard Trieu08062aa2011-09-06 21:01:04 +00005896 if (LHS.get()->getType()->isVectorType() ||
5897 RHS.get()->getType()->isVectorType()) {
5898 if (LHS.get()->getType()->hasIntegerRepresentation() &&
5899 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00005900 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00005901 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00005902 }
Steve Naroff90045e82007-07-13 23:32:42 +00005903
Richard Trieuccd891a2011-09-09 01:45:06 +00005904 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00005905 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005906 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005907
Richard Trieu08062aa2011-09-06 21:01:04 +00005908 if (!LHS.get()->getType()->isIntegerType() ||
5909 !RHS.get()->getType()->isIntegerType())
5910 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005911
Chris Lattner7ef655a2010-01-12 21:23:57 +00005912 // Check for remainder by zero.
Richard Trieu08062aa2011-09-06 21:01:04 +00005913 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00005914 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00005915 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5916 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005917
Chris Lattner7ef655a2010-01-12 21:23:57 +00005918 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005919}
5920
Chandler Carruth13b21be2011-06-27 08:02:19 +00005921/// \brief Diagnose invalid arithmetic on two void pointers.
5922static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00005923 Expr *LHSExpr, Expr *RHSExpr) {
Chandler Carruth13b21be2011-06-27 08:02:19 +00005924 S.Diag(Loc, S.getLangOptions().CPlusPlus
5925 ? diag::err_typecheck_pointer_arith_void_type
5926 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00005927 << 1 /* two pointers */ << LHSExpr->getSourceRange()
5928 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00005929}
5930
5931/// \brief Diagnose invalid arithmetic on a void pointer.
5932static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5933 Expr *Pointer) {
5934 S.Diag(Loc, S.getLangOptions().CPlusPlus
5935 ? diag::err_typecheck_pointer_arith_void_type
5936 : diag::ext_gnu_void_ptr)
5937 << 0 /* one pointer */ << Pointer->getSourceRange();
5938}
5939
5940/// \brief Diagnose invalid arithmetic on two function pointers.
5941static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5942 Expr *LHS, Expr *RHS) {
5943 assert(LHS->getType()->isAnyPointerType());
5944 assert(RHS->getType()->isAnyPointerType());
5945 S.Diag(Loc, S.getLangOptions().CPlusPlus
5946 ? diag::err_typecheck_pointer_arith_function_type
5947 : diag::ext_gnu_ptr_func_arith)
5948 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5949 // We only show the second type if it differs from the first.
5950 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5951 RHS->getType())
5952 << RHS->getType()->getPointeeType()
5953 << LHS->getSourceRange() << RHS->getSourceRange();
5954}
5955
5956/// \brief Diagnose invalid arithmetic on a function pointer.
5957static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5958 Expr *Pointer) {
5959 assert(Pointer->getType()->isAnyPointerType());
5960 S.Diag(Loc, S.getLangOptions().CPlusPlus
5961 ? diag::err_typecheck_pointer_arith_function_type
5962 : diag::ext_gnu_ptr_func_arith)
5963 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5964 << 0 /* one pointer, so only one type */
5965 << Pointer->getSourceRange();
5966}
5967
Richard Trieud9f19342011-09-12 18:08:02 +00005968/// \brief Emit error if Operand is incomplete pointer type
Richard Trieu097ecd22011-09-02 02:15:37 +00005969///
5970/// \returns True if pointer has incomplete type
5971static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
5972 Expr *Operand) {
5973 if ((Operand->getType()->isPointerType() &&
5974 !Operand->getType()->isDependentType()) ||
5975 Operand->getType()->isObjCObjectPointerType()) {
5976 QualType PointeeTy = Operand->getType()->getPointeeType();
5977 if (S.RequireCompleteType(
5978 Loc, PointeeTy,
5979 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5980 << PointeeTy << Operand->getSourceRange()))
5981 return true;
5982 }
5983 return false;
5984}
5985
Chandler Carruth13b21be2011-06-27 08:02:19 +00005986/// \brief Check the validity of an arithmetic pointer operand.
5987///
5988/// If the operand has pointer type, this code will check for pointer types
5989/// which are invalid in arithmetic operations. These will be diagnosed
5990/// appropriately, including whether or not the use is supported as an
5991/// extension.
5992///
5993/// \returns True when the operand is valid to use (even if as an extension).
5994static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5995 Expr *Operand) {
5996 if (!Operand->getType()->isAnyPointerType()) return true;
5997
5998 QualType PointeeTy = Operand->getType()->getPointeeType();
5999 if (PointeeTy->isVoidType()) {
6000 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6001 return !S.getLangOptions().CPlusPlus;
6002 }
6003 if (PointeeTy->isFunctionType()) {
6004 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6005 return !S.getLangOptions().CPlusPlus;
6006 }
6007
Richard Trieu097ecd22011-09-02 02:15:37 +00006008 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006009
6010 return true;
6011}
6012
6013/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6014/// operands.
6015///
6016/// This routine will diagnose any invalid arithmetic on pointer operands much
6017/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6018/// for emitting a single diagnostic even for operations where both LHS and RHS
6019/// are (potentially problematic) pointers.
6020///
6021/// \returns True when the operand is valid to use (even if as an extension).
6022static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006023 Expr *LHSExpr, Expr *RHSExpr) {
6024 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6025 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006026 if (!isLHSPointer && !isRHSPointer) return true;
6027
6028 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00006029 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6030 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006031
6032 // Check for arithmetic on pointers to incomplete types.
6033 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6034 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6035 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006036 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6037 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6038 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006039
6040 return !S.getLangOptions().CPlusPlus;
6041 }
6042
6043 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6044 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6045 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006046 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6047 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6048 RHSExpr);
6049 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006050
6051 return !S.getLangOptions().CPlusPlus;
6052 }
6053
Richard Trieudef75842011-09-06 21:13:51 +00006054 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6055 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00006056
Chandler Carruth13b21be2011-06-27 08:02:19 +00006057 return true;
6058}
6059
Richard Trieudb44a6b2011-09-01 22:53:23 +00006060/// \brief Check bad cases where we step over interface counts.
6061static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6062 SourceLocation OpLoc,
6063 Expr *Op) {
6064 assert(Op->getType()->isAnyPointerType());
6065 QualType PointeeTy = Op->getType()->getPointeeType();
6066 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6067 return true;
6068
6069 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6070 << PointeeTy << Op->getSourceRange();
6071 return false;
6072}
6073
Richard Trieud9f19342011-09-12 18:08:02 +00006074/// \brief Emit error when two pointers are incompatible.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006075static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006076 Expr *LHSExpr, Expr *RHSExpr) {
6077 assert(LHSExpr->getType()->isAnyPointerType());
6078 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00006079 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00006080 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6081 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00006082}
6083
Chris Lattner7ef655a2010-01-12 21:23:57 +00006084QualType Sema::CheckAdditionOperands( // C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006085 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006086 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6087
Richard Trieudef75842011-09-06 21:13:51 +00006088 if (LHS.get()->getType()->isVectorType() ||
6089 RHS.get()->getType()->isVectorType()) {
6090 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006091 if (CompLHSTy) *CompLHSTy = compType;
6092 return compType;
6093 }
Steve Naroff49b45262007-07-13 16:58:59 +00006094
Richard Trieudef75842011-09-06 21:13:51 +00006095 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6096 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006097 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006098
Reid Spencer5f016e22007-07-11 17:01:13 +00006099 // handle the common case first (both operands are arithmetic).
Richard Trieudef75842011-09-06 21:13:51 +00006100 if (LHS.get()->getType()->isArithmeticType() &&
6101 RHS.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006102 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006103 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006104 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006105
Eli Friedmand72d16e2008-05-18 18:08:51 +00006106 // Put any potential pointer into PExp
Richard Trieudef75842011-09-06 21:13:51 +00006107 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006108 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00006109 std::swap(PExp, IExp);
6110
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006111 if (!PExp->getType()->isAnyPointerType())
6112 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006113
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006114 if (!IExp->getType()->isIntegerType())
6115 return InvalidOperands(Loc, LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006116
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006117 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6118 return QualType();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006119
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006120 // Diagnose bad cases where we step over interface counts.
6121 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6122 return QualType();
6123
6124 // Check array bounds for pointer arithemtic
6125 CheckArrayAccess(PExp, IExp);
6126
6127 if (CompLHSTy) {
6128 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6129 if (LHSTy.isNull()) {
6130 LHSTy = LHS.get()->getType();
6131 if (LHSTy->isPromotableIntegerType())
6132 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006133 }
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006134 *CompLHSTy = LHSTy;
Eli Friedmand72d16e2008-05-18 18:08:51 +00006135 }
6136
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006137 return PExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006138}
6139
Chris Lattnereca7be62008-04-07 05:30:13 +00006140// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006141QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006142 SourceLocation Loc,
6143 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006144 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6145
Richard Trieudef75842011-09-06 21:13:51 +00006146 if (LHS.get()->getType()->isVectorType() ||
6147 RHS.get()->getType()->isVectorType()) {
6148 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006149 if (CompLHSTy) *CompLHSTy = compType;
6150 return compType;
6151 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006152
Richard Trieudef75842011-09-06 21:13:51 +00006153 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6154 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006155 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006156
Chris Lattner6e4ab612007-12-09 21:53:25 +00006157 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006158
Chris Lattner6e4ab612007-12-09 21:53:25 +00006159 // Handle the common case first (both operands are arithmetic).
Richard Trieudef75842011-09-06 21:13:51 +00006160 if (LHS.get()->getType()->isArithmeticType() &&
6161 RHS.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006162 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006163 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006164 }
Mike Stump1eb44332009-09-09 15:08:12 +00006165
Chris Lattner6e4ab612007-12-09 21:53:25 +00006166 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00006167 if (LHS.get()->getType()->isAnyPointerType()) {
6168 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006169
Chris Lattnerb5f15622009-04-24 23:50:08 +00006170 // Diagnose bad cases where we step over interface counts.
Richard Trieudef75842011-09-06 21:13:51 +00006171 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006172 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006173
Chris Lattner6e4ab612007-12-09 21:53:25 +00006174 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00006175 if (RHS.get()->getType()->isIntegerType()) {
6176 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006177 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006178
Richard Trieudef75842011-09-06 21:13:51 +00006179 Expr *IExpr = RHS.get()->IgnoreParenCasts();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006180 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6181 OK_Ordinary, IExpr->getExprLoc());
6182 // Check array bounds for pointer arithemtic
Richard Trieudef75842011-09-06 21:13:51 +00006183 CheckArrayAccess(LHS.get()->IgnoreParenCasts(), &negRex);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006184
Richard Trieudef75842011-09-06 21:13:51 +00006185 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6186 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006187 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006188
Chris Lattner6e4ab612007-12-09 21:53:25 +00006189 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006190 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00006191 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006192 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006193
Eli Friedman88d936b2009-05-16 13:54:38 +00006194 if (getLangOptions().CPlusPlus) {
6195 // Pointee types must be the same: C++ [expr.add]
6196 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00006197 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006198 }
6199 } else {
6200 // Pointee types must be compatible C99 6.5.6p3
6201 if (!Context.typesAreCompatible(
6202 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6203 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00006204 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006205 return QualType();
6206 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006207 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006208
Chandler Carruth13b21be2011-06-27 08:02:19 +00006209 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006210 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006211 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006212
Richard Trieudef75842011-09-06 21:13:51 +00006213 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006214 return Context.getPointerDiffType();
6215 }
6216 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006217
Richard Trieudef75842011-09-06 21:13:51 +00006218 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006219}
6220
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006221static bool isScopedEnumerationType(QualType T) {
6222 if (const EnumType *ET = dyn_cast<EnumType>(T))
6223 return ET->getDecl()->isScoped();
6224 return false;
6225}
6226
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006227static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00006228 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006229 QualType LHSType) {
Chandler Carruth21206d52011-02-23 23:34:11 +00006230 llvm::APSInt Right;
6231 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006232 if (RHS.get()->isValueDependent() ||
6233 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006234 return;
6235
6236 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006237 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006238 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006239 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006240 return;
6241 }
6242 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006243 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006244 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006245 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006246 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006247 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006248 return;
6249 }
6250 if (Opc != BO_Shl)
6251 return;
6252
6253 // When left shifting an ICE which is signed, we can check for overflow which
6254 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6255 // integers have defined behavior modulo one more than the maximum value
6256 // representable in the result type, so never warn for those.
6257 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006258 if (LHS.get()->isValueDependent() ||
6259 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6260 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00006261 return;
6262 llvm::APInt ResultBits =
6263 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6264 if (LeftBits.uge(ResultBits))
6265 return;
6266 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6267 Result = Result.shl(Right);
6268
Ted Kremenekfa821382011-06-15 00:54:52 +00006269 // Print the bit representation of the signed integer as an unsigned
6270 // hexadecimal number.
6271 llvm::SmallString<40> HexResult;
6272 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6273
Chandler Carruth21206d52011-02-23 23:34:11 +00006274 // If we are only missing a sign bit, this is less likely to result in actual
6275 // bugs -- if the result is cast back to an unsigned type, it will have the
6276 // expected value. Thus we place this behind a different warning that can be
6277 // turned off separately if needed.
6278 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006279 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006280 << HexResult.str() << LHSType
6281 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006282 return;
6283 }
6284
6285 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006286 << HexResult.str() << Result.getMinSignedBits() << LHSType
6287 << Left.getBitWidth() << LHS.get()->getSourceRange()
6288 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006289}
6290
Chris Lattnereca7be62008-04-07 05:30:13 +00006291// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006292QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006293 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006294 bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006295 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6296
Chris Lattnerca5eede2007-12-12 05:47:28 +00006297 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006298 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6299 !RHS.get()->getType()->hasIntegerRepresentation())
6300 return InvalidOperands(Loc, LHS, RHS);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006301
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006302 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6303 // hasIntegerRepresentation() above instead of this.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006304 if (isScopedEnumerationType(LHS.get()->getType()) ||
6305 isScopedEnumerationType(RHS.get()->getType())) {
6306 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006307 }
6308
Nate Begeman2207d792009-10-25 02:26:48 +00006309 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006310 if (LHS.get()->getType()->isVectorType() ||
6311 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006312 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006313
Chris Lattnerca5eede2007-12-12 05:47:28 +00006314 // Shifts don't perform usual arithmetic conversions, they just do integer
6315 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006316
John McCall1bc80af2010-12-16 19:28:59 +00006317 // For the LHS, do usual unary conversions, but then reset them away
6318 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006319 ExprResult OldLHS = LHS;
6320 LHS = UsualUnaryConversions(LHS.take());
6321 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006322 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006323 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00006324 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00006325
6326 // The RHS is simpler.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006327 RHS = UsualUnaryConversions(RHS.take());
6328 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006329 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006330
Ryan Flynnd0439682009-08-07 16:20:20 +00006331 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006332 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00006333
Chris Lattnerca5eede2007-12-12 05:47:28 +00006334 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006335 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006336}
6337
Chandler Carruth99919472010-07-10 12:30:03 +00006338static bool IsWithinTemplateSpecialization(Decl *D) {
6339 if (DeclContext *DC = D->getDeclContext()) {
6340 if (isa<ClassTemplateSpecializationDecl>(DC))
6341 return true;
6342 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6343 return FD->isFunctionTemplateSpecialization();
6344 }
6345 return false;
6346}
6347
Richard Trieue648ac32011-09-02 03:48:46 +00006348/// If two different enums are compared, raise a warning.
Richard Trieuba261492011-09-06 21:27:33 +00006349static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6350 ExprResult &RHS) {
6351 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6352 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00006353
6354 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6355 if (!LHSEnumType)
6356 return;
6357 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6358 if (!RHSEnumType)
6359 return;
6360
6361 // Ignore anonymous enums.
6362 if (!LHSEnumType->getDecl()->getIdentifier())
6363 return;
6364 if (!RHSEnumType->getDecl()->getIdentifier())
6365 return;
6366
6367 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6368 return;
6369
6370 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6371 << LHSStrippedType << RHSStrippedType
Richard Trieuba261492011-09-06 21:27:33 +00006372 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00006373}
6374
Richard Trieu7be1be02011-09-02 02:55:45 +00006375/// \brief Diagnose bad pointer comparisons.
6376static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006377 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006378 bool IsError) {
6379 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00006380 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00006381 << LHS.get()->getType() << RHS.get()->getType()
6382 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006383}
6384
6385/// \brief Returns false if the pointers are converted to a composite type,
6386/// true otherwise.
6387static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006388 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006389 // C++ [expr.rel]p2:
6390 // [...] Pointer conversions (4.10) and qualification
6391 // conversions (4.4) are performed on pointer operands (or on
6392 // a pointer operand and a null pointer constant) to bring
6393 // them to their composite pointer type. [...]
6394 //
6395 // C++ [expr.eq]p1 uses the same notion for (in)equality
6396 // comparisons of pointers.
6397
6398 // C++ [expr.eq]p2:
6399 // In addition, pointers to members can be compared, or a pointer to
6400 // member and a null pointer constant. Pointer to member conversions
6401 // (4.11) and qualification conversions (4.4) are performed to bring
6402 // them to a common type. If one operand is a null pointer constant,
6403 // the common type is the type of the other operand. Otherwise, the
6404 // common type is a pointer to member type similar (4.4) to the type
6405 // of one of the operands, with a cv-qualification signature (4.4)
6406 // that is the union of the cv-qualification signatures of the operand
6407 // types.
6408
Richard Trieuba261492011-09-06 21:27:33 +00006409 QualType LHSType = LHS.get()->getType();
6410 QualType RHSType = RHS.get()->getType();
6411 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6412 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00006413
6414 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006415 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00006416 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006417 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00006418 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00006419 return true;
6420 }
6421
6422 if (NonStandardCompositeType)
6423 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00006424 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6425 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006426
Richard Trieuba261492011-09-06 21:27:33 +00006427 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6428 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00006429 return false;
6430}
6431
6432static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006433 ExprResult &LHS,
6434 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006435 bool IsError) {
6436 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6437 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00006438 << LHS.get()->getType() << RHS.get()->getType()
6439 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006440}
6441
Douglas Gregor0c6db942009-05-04 06:07:12 +00006442// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00006443QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006444 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006445 bool IsRelational) {
Richard Trieu481037f2011-09-16 00:53:10 +00006446 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6447
John McCall2de56d12010-08-25 11:45:40 +00006448 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006449
Chris Lattner02dd4b12009-12-05 05:40:13 +00006450 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006451 if (LHS.get()->getType()->isVectorType() ||
6452 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006453 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006454
Richard Trieuf1775fb2011-09-06 21:43:51 +00006455 QualType LHSType = LHS.get()->getType();
6456 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00006457
Richard Trieuf1775fb2011-09-06 21:43:51 +00006458 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6459 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006460
Richard Trieuf1775fb2011-09-06 21:43:51 +00006461 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth543cb652011-02-17 08:37:06 +00006462
Richard Trieuf1775fb2011-09-06 21:43:51 +00006463 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00006464 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006465 !LHS.get()->getLocStart().isMacroID() &&
6466 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006467 // For non-floating point types, check for self-comparisons of the form
6468 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6469 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006470 //
6471 // NOTE: Don't warn about comparison expressions resulting from macro
6472 // expansion. Also don't warn about comparisons which are only self
6473 // comparisons within a template specialization. The warnings should catch
6474 // obvious cases in the definition of the template anyways. The idea is to
6475 // warn when the typed comparison operator will always evaluate to the same
6476 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006477 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006478 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006479 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006480 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006481 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006482 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006483 << (Opc == BO_EQ
6484 || Opc == BO_LE
6485 || Opc == BO_GE));
Richard Trieuf1775fb2011-09-06 21:43:51 +00006486 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregord64fdd02010-06-08 19:50:34 +00006487 !DRL->getDecl()->getType()->isReferenceType() &&
6488 !DRR->getDecl()->getType()->isReferenceType()) {
6489 // what is it always going to eval to?
6490 char always_evals_to;
6491 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006492 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006493 always_evals_to = 0; // false
6494 break;
John McCall2de56d12010-08-25 11:45:40 +00006495 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006496 always_evals_to = 1; // true
6497 break;
6498 default:
6499 // best we can say is 'a constant'
6500 always_evals_to = 2; // e.g. array1 <= array2
6501 break;
6502 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006503 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006504 << 1 // array
6505 << always_evals_to);
6506 }
6507 }
Chandler Carruth99919472010-07-10 12:30:03 +00006508 }
Mike Stump1eb44332009-09-09 15:08:12 +00006509
Chris Lattner55660a72009-03-08 19:39:53 +00006510 if (isa<CastExpr>(LHSStripped))
6511 LHSStripped = LHSStripped->IgnoreParenCasts();
6512 if (isa<CastExpr>(RHSStripped))
6513 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006514
Chris Lattner55660a72009-03-08 19:39:53 +00006515 // Warn about comparisons against a string constant (unless the other
6516 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006517 Expr *literalString = 0;
6518 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006519 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006520 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006521 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006522 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006523 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006524 } else if ((isa<StringLiteral>(RHSStripped) ||
6525 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006526 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006527 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006528 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006529 literalStringStripped = RHSStripped;
6530 }
6531
6532 if (literalString) {
6533 std::string resultComparison;
6534 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006535 case BO_LT: resultComparison = ") < 0"; break;
6536 case BO_GT: resultComparison = ") > 0"; break;
6537 case BO_LE: resultComparison = ") <= 0"; break;
6538 case BO_GE: resultComparison = ") >= 0"; break;
6539 case BO_EQ: resultComparison = ") == 0"; break;
6540 case BO_NE: resultComparison = ") != 0"; break;
David Blaikieb219cfc2011-09-23 05:06:16 +00006541 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregora86b8322009-04-06 18:45:53 +00006542 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006543
Ted Kremenek351ba912011-02-23 01:52:04 +00006544 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006545 PDiag(diag::warn_stringcompare)
6546 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006547 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006548 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006549 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006550
Douglas Gregord64fdd02010-06-08 19:50:34 +00006551 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieuf1775fb2011-09-06 21:43:51 +00006552 if (LHS.get()->getType()->isArithmeticType() &&
6553 RHS.get()->getType()->isArithmeticType()) {
6554 UsualArithmeticConversions(LHS, RHS);
6555 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006556 return QualType();
6557 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00006558 else {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006559 LHS = UsualUnaryConversions(LHS.take());
6560 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006561 return QualType();
6562
Richard Trieuf1775fb2011-09-06 21:43:51 +00006563 RHS = UsualUnaryConversions(RHS.take());
6564 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006565 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006566 }
6567
Richard Trieuf1775fb2011-09-06 21:43:51 +00006568 LHSType = LHS.get()->getType();
6569 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006570
Douglas Gregor447b69e2008-11-19 03:25:36 +00006571 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00006572 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00006573
Richard Trieuccd891a2011-09-09 01:45:06 +00006574 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006575 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006576 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006577 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006578 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006579 if (LHSType->hasFloatingRepresentation())
6580 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006581
Richard Trieuf1775fb2011-09-06 21:43:51 +00006582 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006583 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006584 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006585
Richard Trieuf1775fb2011-09-06 21:43:51 +00006586 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006587 Expr::NPC_ValueDependentIsNull);
Richard Trieuf1775fb2011-09-06 21:43:51 +00006588 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006589 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006590
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006591 // All of the following pointer-related warnings are GCC extensions, except
6592 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006593 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00006594 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00006595 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00006596 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00006597 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006598
Douglas Gregor0c6db942009-05-04 06:07:12 +00006599 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00006600 if (LCanPointeeTy == RCanPointeeTy)
6601 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00006602 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006603 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6604 // Valid unless comparison between non-null pointer and function pointer
6605 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006606 // In a SFINAE context, we treat this as a hard error to maintain
6607 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006608 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6609 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006610 diagnoseFunctionPointerToVoidComparison(
Richard Trieuf1775fb2011-09-06 21:43:51 +00006611 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006612
6613 if (isSFINAEContext())
6614 return QualType();
6615
Richard Trieuf1775fb2011-09-06 21:43:51 +00006616 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006617 return ResultTy;
6618 }
6619 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006620
Richard Trieuf1775fb2011-09-06 21:43:51 +00006621 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00006622 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00006623 else
6624 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00006625 }
Eli Friedman3075e762009-08-23 00:27:47 +00006626 // C99 6.5.9p2 and C99 6.5.8p2
6627 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6628 RCanPointeeTy.getUnqualifiedType())) {
6629 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00006630 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00006631 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006632 << LHSType << RHSType << LHS.get()->getSourceRange()
6633 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00006634 }
Richard Trieuccd891a2011-09-09 01:45:06 +00006635 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00006636 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6637 // Valid unless comparison between non-null pointer and function pointer
6638 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00006639 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006640 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00006641 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00006642 } else {
6643 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00006644 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00006645 }
John McCall34d6f932011-03-11 04:25:25 +00006646 if (LCanPointeeTy != RCanPointeeTy) {
6647 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006648 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006649 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00006650 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006651 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00006652 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00006653 }
Mike Stump1eb44332009-09-09 15:08:12 +00006654
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006655 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006656 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006657 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006658 return ResultTy;
6659
Mike Stump1eb44332009-09-09 15:08:12 +00006660 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00006661 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00006662 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006663 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00006664 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006665 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6666 RHS = ImpCastExprToType(RHS.take(), LHSType,
6667 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006668 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006669 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006670 return ResultTy;
6671 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006672 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006673 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00006674 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006675 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6676 LHS = ImpCastExprToType(LHS.take(), RHSType,
6677 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006678 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006679 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006680 return ResultTy;
6681 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006682
6683 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00006684 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006685 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6686 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00006687 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00006688 else
6689 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00006690 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006691
6692 // Handle scoped enumeration types specifically, since they don't promote
6693 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006694 if (LHS.get()->getType()->isEnumeralType() &&
6695 Context.hasSameUnqualifiedType(LHS.get()->getType(),
6696 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00006697 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006698 }
Mike Stump1eb44332009-09-09 15:08:12 +00006699
Steve Naroff1c7d0672008-09-04 15:10:53 +00006700 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00006701 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006702 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00006703 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6704 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006705
Steve Naroff1c7d0672008-09-04 15:10:53 +00006706 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00006707 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006708 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006709 << LHSType << RHSType << LHS.get()->getSourceRange()
6710 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00006711 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00006712 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006713 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006714 }
John Wiegley429bb272011-04-08 18:41:53 +00006715
Steve Naroff59f53942008-09-28 01:11:11 +00006716 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00006717 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00006718 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6719 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00006720 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006721 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006722 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00006723 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006724 ->getPointeeType()->isVoidType())))
6725 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006726 << LHSType << RHSType << LHS.get()->getSourceRange()
6727 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00006728 }
John McCall34d6f932011-03-11 04:25:25 +00006729 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00006730 LHS = ImpCastExprToType(LHS.take(), RHSType,
6731 RHSType->isPointerType() ? CK_BitCast
6732 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00006733 else
John McCall1d9b3b22011-09-09 05:25:32 +00006734 RHS = ImpCastExprToType(RHS.take(), LHSType,
6735 LHSType->isPointerType() ? CK_BitCast
6736 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006737 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00006738 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00006739
Richard Trieuf1775fb2011-09-06 21:43:51 +00006740 if (LHSType->isObjCObjectPointerType() ||
6741 RHSType->isObjCObjectPointerType()) {
6742 const PointerType *LPT = LHSType->getAs<PointerType>();
6743 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00006744 if (LPT || RPT) {
6745 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6746 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006747
Steve Naroffa8069f12008-11-17 19:49:16 +00006748 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006749 !Context.typesAreCompatible(LHSType, RHSType)) {
6750 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00006751 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00006752 }
John McCall34d6f932011-03-11 04:25:25 +00006753 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00006754 LHS = ImpCastExprToType(LHS.take(), RHSType,
6755 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00006756 else
John McCall1d9b3b22011-09-09 05:25:32 +00006757 RHS = ImpCastExprToType(RHS.take(), LHSType,
6758 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006759 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00006760 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00006761 if (LHSType->isObjCObjectPointerType() &&
6762 RHSType->isObjCObjectPointerType()) {
6763 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6764 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00006765 /*isError*/false);
John McCall34d6f932011-03-11 04:25:25 +00006766 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006767 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006768 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00006769 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006770 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00006771 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00006772 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00006773 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6774 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006775 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006776 bool isError = false;
Richard Trieuf1775fb2011-09-06 21:43:51 +00006777 if ((LHSIsNull && LHSType->isIntegerType()) ||
6778 (RHSIsNull && RHSType->isIntegerType())) {
Richard Trieuccd891a2011-09-09 01:45:06 +00006779 if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006780 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Richard Trieuccd891a2011-09-09 01:45:06 +00006781 } else if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006782 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006783 else if (getLangOptions().CPlusPlus) {
6784 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6785 isError = true;
6786 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006787 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00006788
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006789 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006790 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006791 << LHSType << RHSType << LHS.get()->getSourceRange()
6792 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006793 if (isError)
6794 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00006795 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006796
Richard Trieuf1775fb2011-09-06 21:43:51 +00006797 if (LHSType->isIntegerType())
6798 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00006799 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006800 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00006801 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00006802 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006803 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006804 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006805
Steve Naroff39218df2008-09-04 16:56:14 +00006806 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00006807 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00006808 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6809 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006810 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006811 }
Richard Trieuccd891a2011-09-09 01:45:06 +00006812 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00006813 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6814 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006815 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006816 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006817
Richard Trieuf1775fb2011-09-06 21:43:51 +00006818 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006819}
6820
Nate Begemanbe2341d2008-07-14 18:02:46 +00006821/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00006822/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006823/// like a scalar comparison, a vector comparison produces a vector of integer
6824/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006825QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006826 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006827 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00006828 // Check to make sure we're operating on vectors of the same type and width,
6829 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006830 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00006831 if (vType.isNull())
6832 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006833
Richard Trieu9f60dee2011-09-07 01:19:57 +00006834 QualType LHSType = LHS.get()->getType();
6835 QualType RHSType = RHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006836
Anton Yartsev7870b132011-03-27 15:36:07 +00006837 // If AltiVec, the comparison results in a numeric type, i.e.
6838 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00006839 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00006840 return Context.getLogicalOperationType();
6841
Nate Begemanbe2341d2008-07-14 18:02:46 +00006842 // For non-floating point types, check for self-comparisons of the form
6843 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6844 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006845 if (!LHSType->hasFloatingRepresentation()) {
6846 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
6847 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParens()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006848 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00006849 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00006850 PDiag(diag::warn_comparison_always)
6851 << 0 // self-
6852 << 2 // "a constant"
6853 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00006854 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006855
Nate Begemanbe2341d2008-07-14 18:02:46 +00006856 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00006857 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00006858 assert (RHSType->hasFloatingRepresentation());
6859 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00006860 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006861
Nate Begemanbe2341d2008-07-14 18:02:46 +00006862 // Return the type for the comparison, which is the same as vector type for
6863 // integer vectors, or an integer type of identical size and number of
6864 // elements for floating point vectors.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006865 if (LHSType->hasIntegerRepresentation())
6866 return LHSType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006867
Richard Trieu9f60dee2011-09-07 01:19:57 +00006868 const VectorType *VTy = LHSType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00006869 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00006870 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006871 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00006872 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00006873 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6874
Mike Stumpeed9cac2009-02-19 03:04:26 +00006875 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00006876 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00006877 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6878}
6879
Reid Spencer5f016e22007-07-11 17:01:13 +00006880inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00006881 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006882 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6883
Richard Trieu9f60dee2011-09-07 01:19:57 +00006884 if (LHS.get()->getType()->isVectorType() ||
6885 RHS.get()->getType()->isVectorType()) {
6886 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6887 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00006888 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00006889
Richard Trieu9f60dee2011-09-07 01:19:57 +00006890 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00006891 }
Steve Naroff90045e82007-07-13 23:32:42 +00006892
Richard Trieu9f60dee2011-09-07 01:19:57 +00006893 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
6894 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00006895 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00006896 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006897 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00006898 LHS = LHSResult.take();
6899 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006900
Richard Trieu9f60dee2011-09-07 01:19:57 +00006901 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6902 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006903 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00006904 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006905}
6906
6907inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00006908 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00006909
6910 // Diagnose cases where the user write a logical and/or but probably meant a
6911 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6912 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006913 if (LHS.get()->getType()->isIntegerType() &&
6914 !LHS.get()->getType()->isBooleanType() &&
6915 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00006916 // Don't warn in macros or template instantiations.
6917 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00006918 // If the RHS can be constant folded, and if it constant folds to something
6919 // that isn't 0 or 1 (which indicate a potential logical operation that
6920 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00006921 // Parens on the RHS are ignored.
Chris Lattnerb7690b42010-07-24 01:10:11 +00006922 Expr::EvalResult Result;
Richard Trieu9f60dee2011-09-07 01:19:57 +00006923 if (RHS.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6924 if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) ||
Chandler Carruth0683a142011-05-31 05:41:42 +00006925 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6926 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00006927 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006928 << (Opc == BO_LAnd ? "&&" : "||");
6929 // Suggest replacing the logical operator with the bitwise version
6930 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6931 << (Opc == BO_LAnd ? "&" : "|")
6932 << FixItHint::CreateReplacement(SourceRange(
6933 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6934 getLangOptions())),
6935 Opc == BO_LAnd ? "&" : "|");
6936 if (Opc == BO_LAnd)
6937 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6938 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6939 << FixItHint::CreateRemoval(
6940 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00006941 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006942 0, getSourceManager(),
6943 getLangOptions()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00006944 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006945 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00006946 }
Chris Lattner90a8f272010-07-13 19:41:32 +00006947
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006948 if (!Context.getLangOptions().CPlusPlus) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00006949 LHS = UsualUnaryConversions(LHS.take());
6950 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006951 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006952
Richard Trieu9f60dee2011-09-07 01:19:57 +00006953 RHS = UsualUnaryConversions(RHS.take());
6954 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006955 return QualType();
6956
Richard Trieu9f60dee2011-09-07 01:19:57 +00006957 if (!LHS.get()->getType()->isScalarType() ||
6958 !RHS.get()->getType()->isScalarType())
6959 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006960
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006961 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00006962 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006963
John McCall75f7c0f2010-06-04 00:29:51 +00006964 // The following is safe because we only use this method for
6965 // non-overloadable operands.
6966
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006967 // C++ [expr.log.and]p1
6968 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00006969 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006970 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
6971 if (LHSRes.isInvalid())
6972 return InvalidOperands(Loc, LHS, RHS);
6973 LHS = move(LHSRes);
John Wiegley429bb272011-04-08 18:41:53 +00006974
Richard Trieu9f60dee2011-09-07 01:19:57 +00006975 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
6976 if (RHSRes.isInvalid())
6977 return InvalidOperands(Loc, LHS, RHS);
6978 RHS = move(RHSRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006979
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006980 // C++ [expr.log.and]p2
6981 // C++ [expr.log.or]p2
6982 // The result is a bool.
6983 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006984}
6985
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006986/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6987/// is a read-only property; return true if so. A readonly property expression
6988/// depends on various declarations and thus must be treated specially.
6989///
Mike Stump1eb44332009-09-09 15:08:12 +00006990static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006991 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6992 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00006993 if (PropExpr->isImplicitProperty()) return false;
6994
6995 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6996 QualType BaseType = PropExpr->isSuperReceiver() ?
6997 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00006998 PropExpr->getBase()->getType();
6999
John McCall12f78a62010-12-02 01:19:52 +00007000 if (const ObjCObjectPointerType *OPT =
7001 BaseType->getAsObjCInterfacePointerType())
7002 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7003 if (S.isPropertyReadonly(PDecl, IFace))
7004 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007005 }
7006 return false;
7007}
7008
Fariborz Jahanian14086762011-03-28 23:47:18 +00007009static bool IsConstProperty(Expr *E, Sema &S) {
7010 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7011 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7012 if (PropExpr->isImplicitProperty()) return false;
7013
7014 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7015 QualType T = PDecl->getType();
7016 if (T->isReferenceType())
Fariborz Jahanian61750f22011-03-30 16:59:30 +00007017 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanian14086762011-03-28 23:47:18 +00007018 CanQualType CT = S.Context.getCanonicalType(T);
7019 return CT.isConstQualified();
7020 }
7021 return false;
7022}
7023
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007024static bool IsReadonlyMessage(Expr *E, Sema &S) {
7025 if (E->getStmtClass() != Expr::MemberExprClass)
7026 return false;
7027 const MemberExpr *ME = cast<MemberExpr>(E);
7028 NamedDecl *Member = ME->getMemberDecl();
7029 if (isa<FieldDecl>(Member)) {
7030 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7031 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7032 return false;
7033 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7034 }
7035 return false;
7036}
7037
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007038/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7039/// emit an error and return true. If so, return false.
7040static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007041 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007042 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007043 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007044 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7045 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian14086762011-03-28 23:47:18 +00007046 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7047 IsLV = Expr::MLV_Valid;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007048 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7049 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007050 if (IsLV == Expr::MLV_Valid)
7051 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007052
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007053 unsigned Diag = 0;
7054 bool NeedType = false;
7055 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00007056 case Expr::MLV_ConstQualified:
7057 Diag = diag::err_typecheck_assign_const;
7058
John McCall7acddac2011-06-17 06:42:21 +00007059 // In ARC, use some specialized diagnostics for occasions where we
7060 // infer 'const'. These are always pseudo-strong variables.
John McCallf85e1932011-06-15 23:02:42 +00007061 if (S.getLangOptions().ObjCAutoRefCount) {
7062 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7063 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7064 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7065
John McCall7acddac2011-06-17 06:42:21 +00007066 // Use the normal diagnostic if it's pseudo-__strong but the
7067 // user actually wrote 'const'.
7068 if (var->isARCPseudoStrong() &&
7069 (!var->getTypeSourceInfo() ||
7070 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7071 // There are two pseudo-strong cases:
7072 // - self
John McCallf85e1932011-06-15 23:02:42 +00007073 ObjCMethodDecl *method = S.getCurMethodDecl();
7074 if (method && var == method->getSelfDecl())
7075 Diag = diag::err_typecheck_arr_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00007076
7077 // - fast enumeration variables
7078 else
John McCallf85e1932011-06-15 23:02:42 +00007079 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00007080
John McCallf85e1932011-06-15 23:02:42 +00007081 SourceRange Assign;
7082 if (Loc != OrigLoc)
7083 Assign = SourceRange(OrigLoc, OrigLoc);
7084 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7085 // We need to preserve the AST regardless, so migration tool
7086 // can do its job.
7087 return false;
7088 }
7089 }
7090 }
7091
7092 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007093 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007094 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7095 NeedType = true;
7096 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007097 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007098 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7099 NeedType = true;
7100 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007101 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007102 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7103 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007104 case Expr::MLV_Valid:
7105 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007106 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007107 case Expr::MLV_MemberFunction:
7108 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007109 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7110 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007111 case Expr::MLV_IncompleteType:
7112 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007113 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007114 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00007115 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00007116 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007117 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7118 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00007119 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007120 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7121 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007122 case Expr::MLV_ReadonlyProperty:
7123 Diag = diag::error_readonly_property_assignment;
7124 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007125 case Expr::MLV_NoSetterProperty:
7126 Diag = diag::error_nosetter_property_assignment;
7127 break;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007128 case Expr::MLV_InvalidMessageExpression:
7129 Diag = diag::error_readonly_message_assignment;
7130 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007131 case Expr::MLV_SubObjCPropertySetting:
7132 Diag = diag::error_no_subobject_property_setting;
7133 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007134 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007135
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007136 SourceRange Assign;
7137 if (Loc != OrigLoc)
7138 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007139 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007140 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007141 else
Mike Stump1eb44332009-09-09 15:08:12 +00007142 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007143 return true;
7144}
7145
7146
7147
7148// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00007149QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007150 SourceLocation Loc,
7151 QualType CompoundType) {
7152 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00007153 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007154 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007155
Richard Trieu268942b2011-09-07 01:33:52 +00007156 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007157 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7158 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007159 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007160 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007161 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007162 // Simple assignment "x = y".
Richard Trieu268942b2011-09-07 01:33:52 +00007163 if (LHSExpr->getObjectKind() == OK_ObjCProperty) {
7164 ExprResult LHSResult = Owned(LHSExpr);
John Wiegley429bb272011-04-08 18:41:53 +00007165 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7166 if (LHSResult.isInvalid())
7167 return QualType();
Richard Trieu268942b2011-09-07 01:33:52 +00007168 LHSExpr = LHSResult.take();
John Wiegley429bb272011-04-08 18:41:53 +00007169 }
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007170 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007171 if (RHS.isInvalid())
7172 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007173 // Special case of NSObject attributes on c-style pointer types.
7174 if (ConvTy == IncompatiblePointer &&
7175 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007176 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007177 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007178 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007179 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007180
John McCallf89e55a2010-11-18 06:31:45 +00007181 if (ConvTy == Compatible &&
7182 getLangOptions().ObjCNonFragileABI &&
7183 LHSType->isObjCObjectType())
7184 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7185 << LHSType;
7186
Chris Lattner2c156472008-08-21 18:04:13 +00007187 // If the RHS is a unary plus or minus, check to see if they = and + are
7188 // right next to each other. If so, the user may have typo'd "x =+ 4"
7189 // instead of "x += 4".
John Wiegley429bb272011-04-08 18:41:53 +00007190 Expr *RHSCheck = RHS.get();
Chris Lattner2c156472008-08-21 18:04:13 +00007191 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7192 RHSCheck = ICE->getSubExpr();
7193 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007194 if ((UO->getOpcode() == UO_Plus ||
7195 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007196 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007197 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007198 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00007199 // And there is a space or other character before the subexpr of the
7200 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007201 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00007202 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007203 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007204 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007205 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007206 }
Chris Lattner2c156472008-08-21 18:04:13 +00007207 }
John McCallf85e1932011-06-15 23:02:42 +00007208
7209 if (ConvTy == Compatible) {
7210 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieu268942b2011-09-07 01:33:52 +00007211 checkRetainCycles(LHSExpr, RHS.get());
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007212 else if (getLangOptions().ObjCAutoRefCount)
Richard Trieu268942b2011-09-07 01:33:52 +00007213 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCallf85e1932011-06-15 23:02:42 +00007214 }
Chris Lattner2c156472008-08-21 18:04:13 +00007215 } else {
7216 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007217 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007218 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007219
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007220 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007221 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007222 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007223
Richard Trieu268942b2011-09-07 01:33:52 +00007224 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007225
Reid Spencer5f016e22007-07-11 17:01:13 +00007226 // C99 6.5.16p3: The type of an assignment expression is the type of the
7227 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007228 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007229 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7230 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007231 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007232 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00007233 return (getLangOptions().CPlusPlus
7234 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007235}
7236
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007237// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007238static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007239 SourceLocation Loc) {
John Wiegley429bb272011-04-08 18:41:53 +00007240 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00007241
John McCallfb8721c2011-04-10 19:13:55 +00007242 LHS = S.CheckPlaceholderExpr(LHS.take());
7243 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007244 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007245 return QualType();
7246
John McCallcf2e5062010-10-12 07:14:40 +00007247 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7248 // operands, but not unary promotions.
7249 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007250
John McCallf6a16482010-12-04 03:47:34 +00007251 // So we treat the LHS as a ignored value, and in C++ we allow the
7252 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007253 LHS = S.IgnoredValueConversions(LHS.take());
7254 if (LHS.isInvalid())
7255 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007256
7257 if (!S.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007258 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7259 if (RHS.isInvalid())
7260 return QualType();
7261 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007262 S.RequireCompleteType(Loc, RHS.get()->getType(),
7263 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007264 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007265
John Wiegley429bb272011-04-08 18:41:53 +00007266 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007267}
7268
Steve Naroff49b45262007-07-13 16:58:59 +00007269/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7270/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007271static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7272 ExprValueKind &VK,
7273 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007274 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007275 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007276 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007277
Chris Lattner3528d352008-11-21 07:05:48 +00007278 QualType ResType = Op->getType();
7279 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007280
John McCall09431682010-11-18 19:01:18 +00007281 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007282 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00007283 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00007284 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007285 return QualType();
7286 }
7287 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007288 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007289 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007290 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007291 } else if (ResType->isAnyPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007292 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007293 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007294 return QualType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00007295
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007296 // Diagnose bad cases where we step over interface counts.
Richard Trieudb44a6b2011-09-01 22:53:23 +00007297 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007298 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007299 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007300 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007301 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007302 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007303 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007304 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007305 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007306 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007307 IsInc, IsPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00007308 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7309 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007310 } else {
John McCall09431682010-11-18 19:01:18 +00007311 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00007312 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007313 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007314 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007315 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007316 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007317 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007318 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007319 // In C++, a prefix increment is the same type as the operand. Otherwise
7320 // (in C or with postfix), the increment is the unqualified type of the
7321 // operand.
Richard Trieuccd891a2011-09-09 01:45:06 +00007322 if (IsPrefix && S.getLangOptions().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007323 VK = VK_LValue;
7324 return ResType;
7325 } else {
7326 VK = VK_RValue;
7327 return ResType.getUnqualifiedType();
7328 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007329}
7330
John Wiegley429bb272011-04-08 18:41:53 +00007331ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCallf6a16482010-12-04 03:47:34 +00007332 assert(E->getValueKind() == VK_LValue &&
7333 E->getObjectKind() == OK_ObjCProperty);
7334 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7335
Douglas Gregor926df6c2011-06-11 01:09:30 +00007336 QualType T = E->getType();
7337 QualType ReceiverType;
7338 if (PRE->isObjectReceiver())
7339 ReceiverType = PRE->getBase()->getType();
7340 else if (PRE->isSuperReceiver())
7341 ReceiverType = PRE->getSuperReceiverType();
7342 else
7343 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7344
John McCallf6a16482010-12-04 03:47:34 +00007345 ExprValueKind VK = VK_RValue;
7346 if (PRE->isImplicitProperty()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00007347 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007348 PRE->getImplicitPropertyGetter()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00007349 T = getMessageSendResultType(ReceiverType, GetterMethod,
7350 PRE->isClassReceiver(),
7351 PRE->isSuperReceiver());
7352 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007353 }
7354 else {
7355 Diag(PRE->getLocation(), diag::err_getter_not_found)
7356 << PRE->getBase()->getType();
7357 }
John McCallf6a16482010-12-04 03:47:34 +00007358 }
Douglas Gregor926df6c2011-06-11 01:09:30 +00007359
7360 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCallf6a16482010-12-04 03:47:34 +00007361 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00007362
7363 ExprResult Result = MaybeBindToTemporary(E);
7364 if (!Result.isInvalid())
7365 E = Result.take();
John Wiegley429bb272011-04-08 18:41:53 +00007366
7367 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00007368}
7369
Richard Trieu67e29332011-08-02 04:35:43 +00007370void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7371 QualType &LHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00007372 assert(LHS.get()->getValueKind() == VK_LValue &&
7373 LHS.get()->getObjectKind() == OK_ObjCProperty);
7374 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCallf6a16482010-12-04 03:47:34 +00007375
John McCallf85e1932011-06-15 23:02:42 +00007376 bool Consumed = false;
7377
John Wiegley429bb272011-04-08 18:41:53 +00007378 if (PropRef->isImplicitProperty()) {
John McCallf6a16482010-12-04 03:47:34 +00007379 // If using property-dot syntax notation for assignment, and there is a
7380 // setter, RHS expression is being passed to the setter argument. So,
7381 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley429bb272011-04-08 18:41:53 +00007382 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCallf6a16482010-12-04 03:47:34 +00007383 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7384 LHSTy = (*P)->getType();
John McCallf85e1932011-06-15 23:02:42 +00007385 Consumed = (getLangOptions().ObjCAutoRefCount &&
7386 (*P)->hasAttr<NSConsumedAttr>());
John McCallf6a16482010-12-04 03:47:34 +00007387
7388 // Otherwise, if the getter returns an l-value, just call that.
7389 } else {
John Wiegley429bb272011-04-08 18:41:53 +00007390 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCallf6a16482010-12-04 03:47:34 +00007391 ExprValueKind VK = Expr::getValueKindForType(Result);
7392 if (VK == VK_LValue) {
John Wiegley429bb272011-04-08 18:41:53 +00007393 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7394 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCallf6a16482010-12-04 03:47:34 +00007395 return;
John McCall12f78a62010-12-02 01:19:52 +00007396 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007397 }
John McCallf85e1932011-06-15 23:02:42 +00007398 } else if (getLangOptions().ObjCAutoRefCount) {
7399 const ObjCMethodDecl *setter
7400 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7401 if (setter) {
7402 ObjCMethodDecl::param_iterator P = setter->param_begin();
7403 LHSTy = (*P)->getType();
7404 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7405 }
John McCallf6a16482010-12-04 03:47:34 +00007406 }
7407
John McCallf85e1932011-06-15 23:02:42 +00007408 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7409 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007410 InitializedEntity Entity =
John McCallf85e1932011-06-15 23:02:42 +00007411 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley429bb272011-04-08 18:41:53 +00007412 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCallf85e1932011-06-15 23:02:42 +00007413 if (!ArgE.isInvalid()) {
John Wiegley429bb272011-04-08 18:41:53 +00007414 RHS = ArgE;
John McCallf85e1932011-06-15 23:02:42 +00007415 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7416 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7417 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007418 }
7419}
7420
7421
Anders Carlsson369dee42008-02-01 07:15:58 +00007422/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007423/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007424/// where the declaration is needed for type checking. We only need to
7425/// handle cases when the expression references a function designator
7426/// or is an lvalue. Here are some examples:
7427/// - &(x) => x
7428/// - &*****f => f for f a function designator.
7429/// - &s.xx => s
7430/// - &s.zz[1].yy -> s, if zz is an array
7431/// - *(x + 1) -> x, if x is an array
7432/// - &"123"[2] -> 0
7433/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007434static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007435 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007436 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007437 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007438 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007439 // If this is an arrow operator, the address is an offset from
7440 // the base's value, so the object the base refers to is
7441 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007442 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007443 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007444 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007445 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007446 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007447 // FIXME: This code shouldn't be necessary! We should catch the implicit
7448 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007449 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7450 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7451 if (ICE->getSubExpr()->getType()->isArrayType())
7452 return getPrimaryDecl(ICE->getSubExpr());
7453 }
7454 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007455 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007456 case Stmt::UnaryOperatorClass: {
7457 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007458
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007459 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007460 case UO_Real:
7461 case UO_Imag:
7462 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007463 return getPrimaryDecl(UO->getSubExpr());
7464 default:
7465 return 0;
7466 }
7467 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007468 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007469 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007470 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007471 // If the result of an implicit cast is an l-value, we care about
7472 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007473 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007474 default:
7475 return 0;
7476 }
7477}
7478
Richard Trieu5520f232011-09-07 21:46:33 +00007479namespace {
7480 enum {
7481 AO_Bit_Field = 0,
7482 AO_Vector_Element = 1,
7483 AO_Property_Expansion = 2,
7484 AO_Register_Variable = 3,
7485 AO_No_Error = 4
7486 };
7487}
Richard Trieu09a26ad2011-09-02 00:47:55 +00007488/// \brief Diagnose invalid operand for address of operations.
7489///
7490/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007491static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7492 Expr *E, unsigned Type) {
7493 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7494}
7495
Reid Spencer5f016e22007-07-11 17:01:13 +00007496/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007497/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007498/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007499/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007500/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007501/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007502/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00007503static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7504 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00007505 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007506 return S.Context.DependentTy;
7507 if (OrigOp->getType() == S.Context.OverloadTy)
7508 return S.Context.OverloadTy;
John McCall755d8492011-04-12 00:42:48 +00007509 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7510 return S.Context.UnknownAnyTy;
John McCall864c0412011-04-26 20:42:42 +00007511 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7512 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7513 << OrigOp->getSourceRange();
7514 return QualType();
7515 }
John McCall9c72c602010-08-27 09:08:28 +00007516
John McCall755d8492011-04-12 00:42:48 +00007517 assert(!OrigOp->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00007518
John McCall9c72c602010-08-27 09:08:28 +00007519 // Make sure to ignore parentheses in subsequent checks
7520 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007521
John McCall09431682010-11-18 19:01:18 +00007522 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007523 // Implement C99-only parts of addressof rules.
7524 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007525 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007526 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7527 // (assuming the deref expression is valid).
7528 return uOp->getSubExpr()->getType();
7529 }
7530 // Technically, there should be a check for array subscript
7531 // expressions here, but the result of one is always an lvalue anyway.
7532 }
John McCall5808ce42011-02-03 08:15:49 +00007533 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007534 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00007535 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007536
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007537 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007538 bool sfinae = S.isSFINAEContext();
7539 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7540 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007541 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007542 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007543 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007544 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007545 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007546 } else if (lval == Expr::LV_MemberFunction) {
7547 // If it's an instance method, make a member pointer.
7548 // The expression must have exactly the form &A::foo.
7549
7550 // If the underlying expression isn't a decl ref, give up.
7551 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007552 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007553 << OrigOp->getSourceRange();
7554 return QualType();
7555 }
7556 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7557 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7558
7559 // The id-expression was parenthesized.
7560 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00007561 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007562 << OrigOp->getSourceRange();
7563
7564 // The method was named without a qualifier.
7565 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007566 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007567 << op->getSourceRange();
7568 }
7569
John McCall09431682010-11-18 19:01:18 +00007570 return S.Context.getMemberPointerType(op->getType(),
7571 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007572 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007573 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007574 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007575 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00007576 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00007577 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00007578 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007579 return QualType();
7580 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007581 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007582 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00007583 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00007584 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007585 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00007586 AddressOfError = AO_Vector_Element;
John McCall7eb0a9e2010-11-24 05:12:34 +00007587 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007588 // cannot take address of a property expression.
Richard Trieu5520f232011-09-07 21:46:33 +00007589 AddressOfError = AO_Property_Expansion;
Steve Naroffbcb2b612008-02-29 23:30:25 +00007590 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007591 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007592 // with the register storage-class specifier.
7593 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00007594 // in C++ it is not error to take address of a register
7595 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00007596 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00007597 !S.getLangOptions().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00007598 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00007599 }
John McCallba135432009-11-21 08:51:07 +00007600 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00007601 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00007602 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00007603 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00007604 // Could be a pointer to member, though, if there is an explicit
7605 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00007606 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00007607 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007608 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00007609 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00007610 S.Diag(OpLoc,
7611 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00007612 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007613 return QualType();
7614 }
Mike Stump1eb44332009-09-09 15:08:12 +00007615
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00007616 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7617 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00007618 return S.Context.getMemberPointerType(op->getType(),
7619 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007620 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00007621 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00007622 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikieb219cfc2011-09-23 05:06:16 +00007623 llvm_unreachable("Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00007624 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00007625
Richard Trieu5520f232011-09-07 21:46:33 +00007626 if (AddressOfError != AO_No_Error) {
7627 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7628 return QualType();
7629 }
7630
Eli Friedman441cf102009-05-16 23:27:50 +00007631 if (lval == Expr::LV_IncompleteVoidType) {
7632 // Taking the address of a void variable is technically illegal, but we
7633 // allow it in cases which are otherwise valid.
7634 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00007635 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00007636 }
7637
Reid Spencer5f016e22007-07-11 17:01:13 +00007638 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00007639 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00007640 return S.Context.getObjCObjectPointerType(op->getType());
7641 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007642}
7643
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007644/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00007645static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7646 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00007647 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007648 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007649
John Wiegley429bb272011-04-08 18:41:53 +00007650 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7651 if (ConvResult.isInvalid())
7652 return QualType();
7653 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007654 QualType OpTy = Op->getType();
7655 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00007656
7657 if (isa<CXXReinterpretCastExpr>(Op)) {
7658 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7659 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7660 Op->getSourceRange());
7661 }
7662
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007663 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7664 // is an incomplete type or void. It would be possible to warn about
7665 // dereferencing a void pointer, but it's completely well-defined, and such a
7666 // warning is unlikely to catch any mistakes.
7667 if (const PointerType *PT = OpTy->getAs<PointerType>())
7668 Result = PT->getPointeeType();
7669 else if (const ObjCObjectPointerType *OPT =
7670 OpTy->getAs<ObjCObjectPointerType>())
7671 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00007672 else {
John McCallfb8721c2011-04-10 19:13:55 +00007673 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007674 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007675 if (PR.take() != Op)
7676 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007677 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007678
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007679 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00007680 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007681 << OpTy << Op->getSourceRange();
7682 return QualType();
7683 }
John McCall09431682010-11-18 19:01:18 +00007684
7685 // Dereferences are usually l-values...
7686 VK = VK_LValue;
7687
7688 // ...except that certain expressions are never l-values in C.
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00007689 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00007690 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007691
7692 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00007693}
7694
John McCall2de56d12010-08-25 11:45:40 +00007695static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007696 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007697 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007698 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007699 default: llvm_unreachable("Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00007700 case tok::periodstar: Opc = BO_PtrMemD; break;
7701 case tok::arrowstar: Opc = BO_PtrMemI; break;
7702 case tok::star: Opc = BO_Mul; break;
7703 case tok::slash: Opc = BO_Div; break;
7704 case tok::percent: Opc = BO_Rem; break;
7705 case tok::plus: Opc = BO_Add; break;
7706 case tok::minus: Opc = BO_Sub; break;
7707 case tok::lessless: Opc = BO_Shl; break;
7708 case tok::greatergreater: Opc = BO_Shr; break;
7709 case tok::lessequal: Opc = BO_LE; break;
7710 case tok::less: Opc = BO_LT; break;
7711 case tok::greaterequal: Opc = BO_GE; break;
7712 case tok::greater: Opc = BO_GT; break;
7713 case tok::exclaimequal: Opc = BO_NE; break;
7714 case tok::equalequal: Opc = BO_EQ; break;
7715 case tok::amp: Opc = BO_And; break;
7716 case tok::caret: Opc = BO_Xor; break;
7717 case tok::pipe: Opc = BO_Or; break;
7718 case tok::ampamp: Opc = BO_LAnd; break;
7719 case tok::pipepipe: Opc = BO_LOr; break;
7720 case tok::equal: Opc = BO_Assign; break;
7721 case tok::starequal: Opc = BO_MulAssign; break;
7722 case tok::slashequal: Opc = BO_DivAssign; break;
7723 case tok::percentequal: Opc = BO_RemAssign; break;
7724 case tok::plusequal: Opc = BO_AddAssign; break;
7725 case tok::minusequal: Opc = BO_SubAssign; break;
7726 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7727 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7728 case tok::ampequal: Opc = BO_AndAssign; break;
7729 case tok::caretequal: Opc = BO_XorAssign; break;
7730 case tok::pipeequal: Opc = BO_OrAssign; break;
7731 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007732 }
7733 return Opc;
7734}
7735
John McCall2de56d12010-08-25 11:45:40 +00007736static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007737 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007738 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007739 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007740 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00007741 case tok::plusplus: Opc = UO_PreInc; break;
7742 case tok::minusminus: Opc = UO_PreDec; break;
7743 case tok::amp: Opc = UO_AddrOf; break;
7744 case tok::star: Opc = UO_Deref; break;
7745 case tok::plus: Opc = UO_Plus; break;
7746 case tok::minus: Opc = UO_Minus; break;
7747 case tok::tilde: Opc = UO_Not; break;
7748 case tok::exclaim: Opc = UO_LNot; break;
7749 case tok::kw___real: Opc = UO_Real; break;
7750 case tok::kw___imag: Opc = UO_Imag; break;
7751 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007752 }
7753 return Opc;
7754}
7755
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007756/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7757/// This warning is only emitted for builtin assignment operations. It is also
7758/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00007759static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007760 SourceLocation OpLoc) {
7761 if (!S.ActiveTemplateInstantiations.empty())
7762 return;
7763 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7764 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007765 LHSExpr = LHSExpr->IgnoreParenImpCasts();
7766 RHSExpr = RHSExpr->IgnoreParenImpCasts();
7767 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7768 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7769 if (!LHSDeclRef || !RHSDeclRef ||
7770 LHSDeclRef->getLocation().isMacroID() ||
7771 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007772 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007773 const ValueDecl *LHSDecl =
7774 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7775 const ValueDecl *RHSDecl =
7776 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7777 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007778 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007779 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007780 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007781 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007782 if (RefTy->getPointeeType().isVolatileQualified())
7783 return;
7784
7785 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00007786 << LHSDeclRef->getType()
7787 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007788}
7789
Douglas Gregoreaebc752008-11-06 23:29:22 +00007790/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7791/// operator @p Opc at location @c TokLoc. This routine only supports
7792/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00007793ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007794 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00007795 Expr *LHSExpr, Expr *RHSExpr) {
7796 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007797 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00007798 // The following two variables are used for compound assignment operators
7799 QualType CompLHSTy; // Type of LHS after promotions for computation
7800 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00007801 ExprValueKind VK = VK_RValue;
7802 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00007803
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007804 // Check if a 'foo<int>' involved in a binary op, identifies a single
7805 // function unambiguously (i.e. an lvalue ala 13.4)
7806 // But since an assignment can trigger target based overload, exclude it in
7807 // our blind search. i.e:
7808 // template<class T> void f(); template<class T, class U> void f(U);
7809 // f<int> == 0; // resolve f<int> blindly
7810 // void (*p)(int); p = f<int>; // resolve f<int> using target
7811 if (Opc != BO_Assign) {
Richard Trieu78ea78b2011-09-07 01:49:20 +00007812 ExprResult resolvedLHS = CheckPlaceholderExpr(LHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007813 if (!resolvedLHS.isUsable()) return ExprError();
Richard Trieu78ea78b2011-09-07 01:49:20 +00007814 LHS = move(resolvedLHS);
John McCall1de4d4e2011-04-07 08:22:57 +00007815
Richard Trieu78ea78b2011-09-07 01:49:20 +00007816 ExprResult resolvedRHS = CheckPlaceholderExpr(RHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007817 if (!resolvedRHS.isUsable()) return ExprError();
Richard Trieu78ea78b2011-09-07 01:49:20 +00007818 RHS = move(resolvedRHS);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007819 }
7820
Douglas Gregoreaebc752008-11-06 23:29:22 +00007821 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007822 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007823 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00007824 if (getLangOptions().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00007825 LHS.get()->getObjectKind() != OK_ObjCProperty) {
7826 VK = LHS.get()->getValueKind();
7827 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007828 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007829 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00007830 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007831 break;
John McCall2de56d12010-08-25 11:45:40 +00007832 case BO_PtrMemD:
7833 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007834 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007835 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00007836 break;
John McCall2de56d12010-08-25 11:45:40 +00007837 case BO_Mul:
7838 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007839 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00007840 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007841 break;
John McCall2de56d12010-08-25 11:45:40 +00007842 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007843 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007844 break;
John McCall2de56d12010-08-25 11:45:40 +00007845 case BO_Add:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007846 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007847 break;
John McCall2de56d12010-08-25 11:45:40 +00007848 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007849 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007850 break;
John McCall2de56d12010-08-25 11:45:40 +00007851 case BO_Shl:
7852 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007853 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007854 break;
John McCall2de56d12010-08-25 11:45:40 +00007855 case BO_LE:
7856 case BO_LT:
7857 case BO_GE:
7858 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007859 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007860 break;
John McCall2de56d12010-08-25 11:45:40 +00007861 case BO_EQ:
7862 case BO_NE:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007863 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007864 break;
John McCall2de56d12010-08-25 11:45:40 +00007865 case BO_And:
7866 case BO_Xor:
7867 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007868 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007869 break;
John McCall2de56d12010-08-25 11:45:40 +00007870 case BO_LAnd:
7871 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007872 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007873 break;
John McCall2de56d12010-08-25 11:45:40 +00007874 case BO_MulAssign:
7875 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007876 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00007877 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007878 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007879 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7880 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007881 break;
John McCall2de56d12010-08-25 11:45:40 +00007882 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007883 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007884 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007885 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7886 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007887 break;
John McCall2de56d12010-08-25 11:45:40 +00007888 case BO_AddAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007889 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7890 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7891 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007892 break;
John McCall2de56d12010-08-25 11:45:40 +00007893 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007894 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7895 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7896 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007897 break;
John McCall2de56d12010-08-25 11:45:40 +00007898 case BO_ShlAssign:
7899 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007900 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007901 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007902 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7903 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007904 break;
John McCall2de56d12010-08-25 11:45:40 +00007905 case BO_AndAssign:
7906 case BO_XorAssign:
7907 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007908 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007909 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007910 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7911 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007912 break;
John McCall2de56d12010-08-25 11:45:40 +00007913 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007914 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
7915 if (getLangOptions().CPlusPlus && !RHS.isInvalid()) {
7916 VK = RHS.get()->getValueKind();
7917 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007918 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00007919 break;
7920 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00007921 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00007922 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007923
7924 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00007925 CheckArrayAccess(LHS.get());
7926 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007927
Eli Friedmanab3a8522009-03-28 01:22:36 +00007928 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00007929 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007930 ResultTy, VK, OK, OpLoc));
Richard Trieu78ea78b2011-09-07 01:49:20 +00007931 if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00007932 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00007933 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007934 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007935 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00007936 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007937 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00007938 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00007939}
7940
Sebastian Redlaee3c932009-10-27 12:10:02 +00007941/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7942/// operators are mixed in a way that suggests that the programmer forgot that
7943/// comparison operators have higher precedence. The most typical example of
7944/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00007945static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00007946 SourceLocation OpLoc, Expr *LHSExpr,
7947 Expr *RHSExpr) {
Sebastian Redlaee3c932009-10-27 12:10:02 +00007948 typedef BinaryOperator BinOp;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007949 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
7950 RHSopc = static_cast<BinOp::Opcode>(-1);
7951 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
7952 LHSopc = BO->getOpcode();
7953 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
7954 RHSopc = BO->getOpcode();
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007955
7956 // Subs are not binary operators.
Richard Trieu78ea78b2011-09-07 01:49:20 +00007957 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007958 return;
7959
7960 // Bitwise operations are sometimes used as eager logical ops.
7961 // Don't diagnose this.
Richard Trieu78ea78b2011-09-07 01:49:20 +00007962 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
7963 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007964 return;
7965
Richard Trieu78ea78b2011-09-07 01:49:20 +00007966 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
7967 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00007968 if (!isLeftComp && !isRightComp) return;
7969
Richard Trieu78ea78b2011-09-07 01:49:20 +00007970 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
7971 OpLoc)
7972 : SourceRange(OpLoc, RHSExpr->getLocEnd());
7973 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
7974 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00007975 SourceRange ParensRange = isLeftComp ?
Richard Trieu78ea78b2011-09-07 01:49:20 +00007976 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
7977 RHSExpr->getLocEnd())
7978 : SourceRange(LHSExpr->getLocStart(),
7979 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00007980
7981 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7982 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7983 SuggestParentheses(Self, OpLoc,
7984 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Richard Trieu78ea78b2011-09-07 01:49:20 +00007985 RHSExpr->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00007986 SuggestParentheses(Self, OpLoc,
7987 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7988 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007989}
7990
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007991/// \brief It accepts a '&' expr that is inside a '|' one.
7992/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7993/// in parentheses.
7994static void
7995EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7996 BinaryOperator *Bop) {
7997 assert(Bop->getOpcode() == BO_And);
7998 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7999 << Bop->getSourceRange() << OpLoc;
8000 SuggestParentheses(Self, Bop->getOperatorLoc(),
8001 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8002 Bop->getSourceRange());
8003}
8004
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008005/// \brief It accepts a '&&' expr that is inside a '||' one.
8006/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8007/// in parentheses.
8008static void
8009EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008010 BinaryOperator *Bop) {
8011 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008012 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8013 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008014 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008015 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008016 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008017}
8018
8019/// \brief Returns true if the given expression can be evaluated as a constant
8020/// 'true'.
8021static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8022 bool Res;
8023 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8024}
8025
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008026/// \brief Returns true if the given expression can be evaluated as a constant
8027/// 'false'.
8028static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8029 bool Res;
8030 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8031}
8032
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008033/// \brief Look for '&&' in the left hand of a '||' expr.
8034static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008035 Expr *LHSExpr, Expr *RHSExpr) {
8036 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008037 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008038 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008039 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008040 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008041 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8042 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8043 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8044 } else if (Bop->getOpcode() == BO_LOr) {
8045 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8046 // If it's "a || b && 1 || c" we didn't warn earlier for
8047 // "a || b && 1", but warn now.
8048 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8049 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8050 }
8051 }
8052 }
8053}
8054
8055/// \brief Look for '&&' in the right hand of a '||' expr.
8056static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008057 Expr *LHSExpr, Expr *RHSExpr) {
8058 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008059 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008060 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008061 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008062 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008063 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8064 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8065 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008066 }
8067 }
8068}
8069
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008070/// \brief Look for '&' in the left or right hand of a '|' expr.
8071static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8072 Expr *OrArg) {
8073 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8074 if (Bop->getOpcode() == BO_And)
8075 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8076 }
8077}
8078
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008079/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008080/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008081static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008082 SourceLocation OpLoc, Expr *LHSExpr,
8083 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008084 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008085 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008086 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008087
8088 // Diagnose "arg1 & arg2 | arg3"
8089 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008090 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8091 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008092 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008093
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008094 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8095 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008096 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008097 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8098 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008099 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008100}
8101
Reid Spencer5f016e22007-07-11 17:01:13 +00008102// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008103ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008104 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00008105 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00008106 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00008107 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8108 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008109
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008110 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00008111 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008112
Richard Trieubefece12011-09-07 02:02:10 +00008113 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008114}
8115
John McCall60d7b3a2010-08-24 06:29:42 +00008116ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008117 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008118 Expr *LHSExpr, Expr *RHSExpr) {
John McCall01b2e4e2010-12-06 05:26:58 +00008119 if (getLangOptions().CPlusPlus) {
8120 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008121
Richard Trieubefece12011-09-07 02:02:10 +00008122 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) {
John McCall01b2e4e2010-12-06 05:26:58 +00008123 UseBuiltinOperator = false;
Richard Trieubefece12011-09-07 02:02:10 +00008124 } else if (Opc == BO_Assign &&
8125 LHSExpr->getObjectKind() == OK_ObjCProperty) {
John McCall01b2e4e2010-12-06 05:26:58 +00008126 UseBuiltinOperator = true;
8127 } else {
Richard Trieubefece12011-09-07 02:02:10 +00008128 UseBuiltinOperator = !LHSExpr->getType()->isOverloadableType() &&
8129 !RHSExpr->getType()->isOverloadableType();
John McCall01b2e4e2010-12-06 05:26:58 +00008130 }
8131
8132 if (!UseBuiltinOperator) {
8133 // Find all of the overloaded operators visible from this
8134 // point. We perform both an operator-name lookup from the local
8135 // scope and an argument-dependent lookup based on the types of
8136 // the arguments.
8137 UnresolvedSet<16> Functions;
8138 OverloadedOperatorKind OverOp
8139 = BinaryOperator::getOverloadedOperator(Opc);
8140 if (S && OverOp != OO_None)
Richard Trieubefece12011-09-07 02:02:10 +00008141 LookupOverloadedOperatorName(OverOp, S, LHSExpr->getType(),
8142 RHSExpr->getType(), Functions);
John McCall01b2e4e2010-12-06 05:26:58 +00008143
8144 // Build the (potentially-overloaded, potentially-dependent)
8145 // binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008146 return CreateOverloadedBinOp(OpLoc, Opc, Functions, LHSExpr, RHSExpr);
John McCall01b2e4e2010-12-06 05:26:58 +00008147 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008148 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008149
Douglas Gregoreaebc752008-11-06 23:29:22 +00008150 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008151 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00008152}
8153
John McCall60d7b3a2010-08-24 06:29:42 +00008154ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008155 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008156 Expr *InputExpr) {
8157 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008158 ExprValueKind VK = VK_RValue;
8159 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008160 QualType resultType;
8161 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008162 case UO_PreInc:
8163 case UO_PreDec:
8164 case UO_PostInc:
8165 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008166 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008167 Opc == UO_PreInc ||
8168 Opc == UO_PostInc,
8169 Opc == UO_PreInc ||
8170 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008171 break;
John McCall2de56d12010-08-25 11:45:40 +00008172 case UO_AddrOf:
John Wiegley429bb272011-04-08 18:41:53 +00008173 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008174 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008175 case UO_Deref: {
John McCallfb8721c2011-04-10 19:13:55 +00008176 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008177 if (!resolved.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008178 Input = move(resolved);
8179 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8180 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008181 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008182 }
John McCall2de56d12010-08-25 11:45:40 +00008183 case UO_Plus:
8184 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008185 Input = UsualUnaryConversions(Input.take());
8186 if (Input.isInvalid()) return ExprError();
8187 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008188 if (resultType->isDependentType())
8189 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008190 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8191 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008192 break;
8193 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8194 resultType->isEnumeralType())
8195 break;
8196 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008197 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008198 resultType->isPointerType())
8199 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008200 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008201 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008202 if (Input.isInvalid()) return ExprError();
8203 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008204 }
Douglas Gregor74253732008-11-19 15:42:04 +00008205
Sebastian Redl0eb23302009-01-19 00:08:26 +00008206 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008207 << resultType << Input.get()->getSourceRange());
8208
John McCall2de56d12010-08-25 11:45:40 +00008209 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008210 Input = UsualUnaryConversions(Input.take());
8211 if (Input.isInvalid()) return ExprError();
8212 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008213 if (resultType->isDependentType())
8214 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008215 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8216 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8217 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008218 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008219 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008220 else if (resultType->hasIntegerRepresentation())
8221 break;
8222 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008223 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008224 if (Input.isInvalid()) return ExprError();
8225 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008226 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008227 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008228 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008229 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008230 break;
John Wiegley429bb272011-04-08 18:41:53 +00008231
John McCall2de56d12010-08-25 11:45:40 +00008232 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008233 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008234 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8235 if (Input.isInvalid()) return ExprError();
8236 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008237 if (resultType->isDependentType())
8238 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008239 if (resultType->isScalarType()) {
8240 // C99 6.5.3.3p1: ok, fallthrough;
8241 if (Context.getLangOptions().CPlusPlus) {
8242 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8243 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008244 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8245 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008246 }
John McCall2cd11fe2010-10-12 02:09:17 +00008247 } else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008248 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008249 if (Input.isInvalid()) return ExprError();
8250 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008251 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008252 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008253 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008254 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008255
Reid Spencer5f016e22007-07-11 17:01:13 +00008256 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008257 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008258 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008259 break;
John McCall2de56d12010-08-25 11:45:40 +00008260 case UO_Real:
8261 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008262 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00008263 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley429bb272011-04-08 18:41:53 +00008264 if (Input.isInvalid()) return ExprError();
8265 if (Input.get()->getValueKind() != VK_RValue &&
8266 Input.get()->getObjectKind() == OK_Ordinary)
8267 VK = Input.get()->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00008268 break;
John McCall2de56d12010-08-25 11:45:40 +00008269 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008270 resultType = Input.get()->getType();
8271 VK = Input.get()->getValueKind();
8272 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008273 break;
8274 }
John Wiegley429bb272011-04-08 18:41:53 +00008275 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008276 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008277
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008278 // Check for array bounds violations in the operand of the UnaryOperator,
8279 // except for the '*' and '&' operators that have to be handled specially
8280 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8281 // that are explicitly defined as valid by the standard).
8282 if (Opc != UO_AddrOf && Opc != UO_Deref)
8283 CheckArrayAccess(Input.get());
8284
John Wiegley429bb272011-04-08 18:41:53 +00008285 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008286 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008287}
8288
John McCall60d7b3a2010-08-24 06:29:42 +00008289ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008290 UnaryOperatorKind Opc, Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00008291 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00008292 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008293 // Find all of the overloaded operators visible from this
8294 // point. We perform both an operator-name lookup from the local
8295 // scope and an argument-dependent lookup based on the types of
8296 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008297 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008298 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008299 if (S && OverOp != OO_None)
8300 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8301 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008302
John McCall9ae2f072010-08-23 23:25:46 +00008303 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008304 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008305
John McCall9ae2f072010-08-23 23:25:46 +00008306 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008307}
8308
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008309// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008310ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008311 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008312 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008313}
8314
Steve Naroff1b273c42007-09-16 14:56:35 +00008315/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008316ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008317 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008318 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008319 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008320 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008321 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008322}
8323
John McCallf85e1932011-06-15 23:02:42 +00008324/// Given the last statement in a statement-expression, check whether
8325/// the result is a producing expression (like a call to an
8326/// ns_returns_retained function) and, if so, rebuild it to hoist the
8327/// release out of the full-expression. Otherwise, return null.
8328/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00008329static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00008330 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00008331 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00008332 if (!cleanups) return 0;
8333
8334 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +00008335 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCallf85e1932011-06-15 23:02:42 +00008336 return 0;
8337
8338 // Splice out the cast. This shouldn't modify any interesting
8339 // features of the statement.
8340 Expr *producer = cast->getSubExpr();
8341 assert(producer->getType() == cast->getType());
8342 assert(producer->getValueKind() == cast->getValueKind());
8343 cleanups->setSubExpr(producer);
8344 return cleanups;
8345}
8346
John McCall60d7b3a2010-08-24 06:29:42 +00008347ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008348Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008349 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008350 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8351 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8352
Douglas Gregordd8f5692010-03-10 04:54:39 +00008353 bool isFileScope
8354 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008355 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008356 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008357
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008358 // FIXME: there are a variety of strange constraints to enforce here, for
8359 // example, it is not possible to goto into a stmt expression apparently.
8360 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008361
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008362 // If there are sub stmts in the compound stmt, take the type of the last one
8363 // as the type of the stmtexpr.
8364 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008365 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008366 if (!Compound->body_empty()) {
8367 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008368 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008369 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008370 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8371 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008372 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008373 }
John McCallf85e1932011-06-15 23:02:42 +00008374
John Wiegley429bb272011-04-08 18:41:53 +00008375 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008376 // Do function/array conversion on the last expression, but not
8377 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00008378 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8379 if (LastExpr.isInvalid())
8380 return ExprError();
8381 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00008382
John Wiegley429bb272011-04-08 18:41:53 +00008383 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00008384 // In ARC, if the final expression ends in a consume, splice
8385 // the consume out and bind it later. In the alternate case
8386 // (when dealing with a retainable type), the result
8387 // initialization will create a produce. In both cases the
8388 // result will be +1, and we'll need to balance that out with
8389 // a bind.
8390 if (Expr *rebuiltLastStmt
8391 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8392 LastExpr = rebuiltLastStmt;
8393 } else {
8394 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008395 InitializedEntity::InitializeResult(LPLoc,
8396 Ty,
8397 false),
8398 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00008399 LastExpr);
8400 }
8401
John Wiegley429bb272011-04-08 18:41:53 +00008402 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008403 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008404 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008405 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00008406 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008407 else
John Wiegley429bb272011-04-08 18:41:53 +00008408 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008409 StmtExprMayBindToTemp = true;
8410 }
8411 }
8412 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008413 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008414
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008415 // FIXME: Check that expression type is complete/non-abstract; statement
8416 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008417 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8418 if (StmtExprMayBindToTemp)
8419 return MaybeBindToTemporary(ResStmtExpr);
8420 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008421}
Steve Naroffd34e9152007-08-01 22:05:33 +00008422
John McCall60d7b3a2010-08-24 06:29:42 +00008423ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008424 TypeSourceInfo *TInfo,
8425 OffsetOfComponent *CompPtr,
8426 unsigned NumComponents,
8427 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008428 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008429 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008430 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008431
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008432 // We must have at least one component that refers to the type, and the first
8433 // one is known to be a field designator. Verify that the ArgTy represents
8434 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008435 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008436 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8437 << ArgTy << TypeRange);
8438
8439 // Type must be complete per C99 7.17p3 because a declaring a variable
8440 // with an incomplete type would be ill-formed.
8441 if (!Dependent
8442 && RequireCompleteType(BuiltinLoc, ArgTy,
8443 PDiag(diag::err_offsetof_incomplete_type)
8444 << TypeRange))
8445 return ExprError();
8446
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008447 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8448 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00008449 // FIXME: This diagnostic isn't actually visible because the location is in
8450 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008451 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008452 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8453 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008454
8455 bool DidWarnAboutNonPOD = false;
8456 QualType CurrentType = ArgTy;
8457 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008458 SmallVector<OffsetOfNode, 4> Comps;
8459 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008460 for (unsigned i = 0; i != NumComponents; ++i) {
8461 const OffsetOfComponent &OC = CompPtr[i];
8462 if (OC.isBrackets) {
8463 // Offset of an array sub-field. TODO: Should we allow vector elements?
8464 if (!CurrentType->isDependentType()) {
8465 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8466 if(!AT)
8467 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8468 << CurrentType);
8469 CurrentType = AT->getElementType();
8470 } else
8471 CurrentType = Context.DependentTy;
8472
8473 // The expression must be an integral expression.
8474 // FIXME: An integral constant expression?
8475 Expr *Idx = static_cast<Expr*>(OC.U.E);
8476 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8477 !Idx->getType()->isIntegerType())
8478 return ExprError(Diag(Idx->getLocStart(),
8479 diag::err_typecheck_subscript_not_integer)
8480 << Idx->getSourceRange());
8481
8482 // Record this array index.
8483 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8484 Exprs.push_back(Idx);
8485 continue;
8486 }
8487
8488 // Offset of a field.
8489 if (CurrentType->isDependentType()) {
8490 // We have the offset of a field, but we can't look into the dependent
8491 // type. Just record the identifier of the field.
8492 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8493 CurrentType = Context.DependentTy;
8494 continue;
8495 }
8496
8497 // We need to have a complete type to look into.
8498 if (RequireCompleteType(OC.LocStart, CurrentType,
8499 diag::err_offsetof_incomplete_type))
8500 return ExprError();
8501
8502 // Look for the designated field.
8503 const RecordType *RC = CurrentType->getAs<RecordType>();
8504 if (!RC)
8505 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8506 << CurrentType);
8507 RecordDecl *RD = RC->getDecl();
8508
8509 // C++ [lib.support.types]p5:
8510 // The macro offsetof accepts a restricted set of type arguments in this
8511 // International Standard. type shall be a POD structure or a POD union
8512 // (clause 9).
8513 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8514 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00008515 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008516 PDiag(diag::warn_offsetof_non_pod_type)
8517 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8518 << CurrentType))
8519 DidWarnAboutNonPOD = true;
8520 }
8521
8522 // Look for the field.
8523 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8524 LookupQualifiedName(R, RD);
8525 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00008526 IndirectFieldDecl *IndirectMemberDecl = 0;
8527 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00008528 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00008529 MemberDecl = IndirectMemberDecl->getAnonField();
8530 }
8531
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008532 if (!MemberDecl)
8533 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8534 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8535 OC.LocEnd));
8536
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00008537 // C99 7.17p3:
8538 // (If the specified member is a bit-field, the behavior is undefined.)
8539 //
8540 // We diagnose this as an error.
8541 if (MemberDecl->getBitWidth()) {
8542 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8543 << MemberDecl->getDeclName()
8544 << SourceRange(BuiltinLoc, RParenLoc);
8545 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8546 return ExprError();
8547 }
Eli Friedman19410a72010-08-05 10:11:36 +00008548
8549 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00008550 if (IndirectMemberDecl)
8551 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00008552
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008553 // If the member was found in a base class, introduce OffsetOfNodes for
8554 // the base class indirections.
8555 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8556 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00008557 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008558 CXXBasePath &Path = Paths.front();
8559 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8560 B != BEnd; ++B)
8561 Comps.push_back(OffsetOfNode(B->Base));
8562 }
Eli Friedman19410a72010-08-05 10:11:36 +00008563
Francois Pichet87c2e122010-11-21 06:08:52 +00008564 if (IndirectMemberDecl) {
8565 for (IndirectFieldDecl::chain_iterator FI =
8566 IndirectMemberDecl->chain_begin(),
8567 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8568 assert(isa<FieldDecl>(*FI));
8569 Comps.push_back(OffsetOfNode(OC.LocStart,
8570 cast<FieldDecl>(*FI), OC.LocEnd));
8571 }
8572 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008573 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00008574
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008575 CurrentType = MemberDecl->getType().getNonReferenceType();
8576 }
8577
8578 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8579 TInfo, Comps.data(), Comps.size(),
8580 Exprs.data(), Exprs.size(), RParenLoc));
8581}
Mike Stumpeed9cac2009-02-19 03:04:26 +00008582
John McCall60d7b3a2010-08-24 06:29:42 +00008583ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00008584 SourceLocation BuiltinLoc,
8585 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008586 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00008587 OffsetOfComponent *CompPtr,
8588 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00008589 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00008590
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008591 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00008592 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008593 if (ArgTy.isNull())
8594 return ExprError();
8595
Eli Friedman5a15dc12010-08-05 10:15:45 +00008596 if (!ArgTInfo)
8597 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8598
8599 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00008600 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008601}
8602
8603
John McCall60d7b3a2010-08-24 06:29:42 +00008604ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008605 Expr *CondExpr,
8606 Expr *LHSExpr, Expr *RHSExpr,
8607 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00008608 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8609
John McCallf89e55a2010-11-18 06:31:45 +00008610 ExprValueKind VK = VK_RValue;
8611 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00008612 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00008613 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00008614 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00008615 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00008616 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00008617 } else {
8618 // The conditional expression is required to be a constant expression.
8619 llvm::APSInt condEval(32);
8620 SourceLocation ExpLoc;
8621 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00008622 return ExprError(Diag(ExpLoc,
8623 diag::err_typecheck_choose_expr_requires_constant)
8624 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00008625
Sebastian Redl28507842009-02-26 14:39:58 +00008626 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00008627 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8628
8629 resType = ActiveExpr->getType();
8630 ValueDependent = ActiveExpr->isValueDependent();
8631 VK = ActiveExpr->getValueKind();
8632 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00008633 }
8634
Sebastian Redlf53597f2009-03-15 17:47:39 +00008635 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008636 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00008637 resType->isDependentType(),
8638 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00008639}
8640
Steve Naroff4eb206b2008-09-03 18:15:37 +00008641//===----------------------------------------------------------------------===//
8642// Clang Extensions.
8643//===----------------------------------------------------------------------===//
8644
8645/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00008646void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008647 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00008648 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008649 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00008650 if (CurScope)
8651 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008652 else
8653 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00008654}
8655
Mike Stump98eb8a72009-02-04 22:31:32 +00008656void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00008657 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00008658 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008659 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008660
John McCallbf1a0282010-06-04 23:28:52 +00008661 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00008662 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00008663
John McCall711c52b2011-01-05 12:14:39 +00008664 // GetTypeForDeclarator always produces a function type for a block
8665 // literal signature. Furthermore, it is always a FunctionProtoType
8666 // unless the function was written with a typedef.
8667 assert(T->isFunctionType() &&
8668 "GetTypeForDeclarator made a non-function block signature");
8669
8670 // Look for an explicit signature in that function type.
8671 FunctionProtoTypeLoc ExplicitSignature;
8672
8673 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8674 if (isa<FunctionProtoTypeLoc>(tmp)) {
8675 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8676
8677 // Check whether that explicit signature was synthesized by
8678 // GetTypeForDeclarator. If so, don't save that as part of the
8679 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00008680 if (ExplicitSignature.getLocalRangeBegin() ==
8681 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00008682 // This would be much cheaper if we stored TypeLocs instead of
8683 // TypeSourceInfos.
8684 TypeLoc Result = ExplicitSignature.getResultLoc();
8685 unsigned Size = Result.getFullDataSize();
8686 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8687 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8688
8689 ExplicitSignature = FunctionProtoTypeLoc();
8690 }
John McCall82dc0092010-06-04 11:21:44 +00008691 }
Mike Stump1eb44332009-09-09 15:08:12 +00008692
John McCall711c52b2011-01-05 12:14:39 +00008693 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8694 CurBlock->FunctionType = T;
8695
8696 const FunctionType *Fn = T->getAs<FunctionType>();
8697 QualType RetTy = Fn->getResultType();
8698 bool isVariadic =
8699 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8700
John McCallc71a4912010-06-04 19:02:56 +00008701 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00008702
John McCall82dc0092010-06-04 11:21:44 +00008703 // Don't allow returning a objc interface by value.
8704 if (RetTy->isObjCObjectType()) {
8705 Diag(ParamInfo.getSourceRange().getBegin(),
8706 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8707 return;
8708 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008709
John McCall82dc0092010-06-04 11:21:44 +00008710 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00008711 // return type. TODO: what should we do with declarators like:
8712 // ^ * { ... }
8713 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00008714 if (RetTy != Context.DependentTy)
8715 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008716
John McCall82dc0092010-06-04 11:21:44 +00008717 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008718 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00008719 if (ExplicitSignature) {
8720 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8721 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008722 if (Param->getIdentifier() == 0 &&
8723 !Param->isImplicit() &&
8724 !Param->isInvalidDecl() &&
8725 !getLangOptions().CPlusPlus)
8726 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00008727 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008728 }
John McCall82dc0092010-06-04 11:21:44 +00008729
8730 // Fake up parameter variables if we have a typedef, like
8731 // ^ fntype { ... }
8732 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8733 for (FunctionProtoType::arg_type_iterator
8734 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8735 ParmVarDecl *Param =
8736 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8737 ParamInfo.getSourceRange().getBegin(),
8738 *I);
John McCallc71a4912010-06-04 19:02:56 +00008739 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00008740 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008741 }
John McCall82dc0092010-06-04 11:21:44 +00008742
John McCallc71a4912010-06-04 19:02:56 +00008743 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00008744 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +00008745 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +00008746 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8747 CurBlock->TheDecl->param_end(),
8748 /*CheckParameterNames=*/false);
8749 }
8750
John McCall82dc0092010-06-04 11:21:44 +00008751 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008752 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00008753
John McCallc71a4912010-06-04 19:02:56 +00008754 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00008755 Diag(ParamInfo.getAttributes()->getLoc(),
8756 diag::warn_attribute_sentinel_not_variadic) << 1;
8757 // FIXME: remove the attribute.
8758 }
8759
8760 // Put the parameter variables in scope. We can bail out immediately
8761 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00008762 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00008763 return;
8764
Steve Naroff090276f2008-10-10 01:28:17 +00008765 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00008766 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8767 (*AI)->setOwningFunction(CurBlock->TheDecl);
8768
Steve Naroff090276f2008-10-10 01:28:17 +00008769 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00008770 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008771 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00008772
Steve Naroff090276f2008-10-10 01:28:17 +00008773 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00008774 }
John McCall7a9813c2010-01-22 00:28:27 +00008775 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008776}
8777
8778/// ActOnBlockError - If there is an error parsing a block, this callback
8779/// is invoked to pop the information about the block from the action impl.
8780void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00008781 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00008782 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008783 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008784}
8785
8786/// ActOnBlockStmtExpr - This is called when the body of a block statement
8787/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00008788ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00008789 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00008790 // If blocks are disabled, emit an error.
8791 if (!LangOpts.Blocks)
8792 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00008793
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008794 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008795
Steve Naroff090276f2008-10-10 01:28:17 +00008796 PopDeclContext();
8797
Steve Naroff4eb206b2008-09-03 18:15:37 +00008798 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00008799 if (!BSI->ReturnType.isNull())
8800 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008801
Mike Stump56925862009-07-28 22:04:01 +00008802 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008803 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00008804
John McCall469a1eb2011-02-02 13:00:07 +00008805 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00008806 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8807 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00008808
John McCallc71a4912010-06-04 19:02:56 +00008809 // If the user wrote a function type in some form, try to use that.
8810 if (!BSI->FunctionType.isNull()) {
8811 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8812
8813 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8814 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8815
8816 // Turn protoless block types into nullary block types.
8817 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00008818 FunctionProtoType::ExtProtoInfo EPI;
8819 EPI.ExtInfo = Ext;
8820 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008821
8822 // Otherwise, if we don't need to change anything about the function type,
8823 // preserve its sugar structure.
8824 } else if (FTy->getResultType() == RetTy &&
8825 (!NoReturn || FTy->getNoReturnAttr())) {
8826 BlockTy = BSI->FunctionType;
8827
8828 // Otherwise, make the minimal modifications to the function type.
8829 } else {
8830 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00008831 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8832 EPI.TypeQuals = 0; // FIXME: silently?
8833 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00008834 BlockTy = Context.getFunctionType(RetTy,
8835 FPT->arg_type_begin(),
8836 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00008837 EPI);
John McCallc71a4912010-06-04 19:02:56 +00008838 }
8839
8840 // If we don't have a function type, just build one from nothing.
8841 } else {
John McCalle23cf432010-12-14 08:05:40 +00008842 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00008843 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00008844 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008845 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008846
John McCallc71a4912010-06-04 19:02:56 +00008847 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8848 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00008849 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008850
Chris Lattner17a78302009-04-19 05:28:12 +00008851 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00008852 if (getCurFunction()->NeedsScopeChecking() &&
8853 !hasAnyUnrecoverableErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00008854 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00008855
Chris Lattnere476bdc2011-02-17 23:58:47 +00008856 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008857
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +00008858 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8859 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8860 const VarDecl *variable = ci->getVariable();
8861 QualType T = variable->getType();
8862 QualType::DestructionKind destructKind = T.isDestructedType();
8863 if (destructKind != QualType::DK_none)
8864 getCurFunction()->setHasBranchProtectedScope();
8865 }
8866
Douglas Gregorf8b7f712011-09-06 20:46:03 +00008867 computeNRVO(Body, getCurBlock());
8868
Benjamin Kramerd2486192011-07-12 14:11:05 +00008869 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8870 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8871 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8872
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008873 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00008874}
8875
John McCall60d7b3a2010-08-24 06:29:42 +00008876ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008877 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008878 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008879 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00008880 GetTypeFromParser(Ty, &TInfo);
8881 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008882}
8883
John McCall60d7b3a2010-08-24 06:29:42 +00008884ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00008885 Expr *E, TypeSourceInfo *TInfo,
8886 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008887 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00008888
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008889 // Get the va_list type
8890 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008891 if (VaListType->isArrayType()) {
8892 // Deal with implicit array decay; for example, on x86-64,
8893 // va_list is an array, but it's supposed to decay to
8894 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008895 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00008896 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00008897 ExprResult Result = UsualUnaryConversions(E);
8898 if (Result.isInvalid())
8899 return ExprError();
8900 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008901 } else {
8902 // Otherwise, the va_list argument must be an l-value because
8903 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00008904 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00008905 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00008906 return ExprError();
8907 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008908
Douglas Gregordd027302009-05-19 23:10:31 +00008909 if (!E->isTypeDependent() &&
8910 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00008911 return ExprError(Diag(E->getLocStart(),
8912 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008913 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00008914 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008915
David Majnemer0adde122011-06-14 05:17:32 +00008916 if (!TInfo->getType()->isDependentType()) {
8917 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8918 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8919 << TInfo->getTypeLoc().getSourceRange()))
8920 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00008921
David Majnemer0adde122011-06-14 05:17:32 +00008922 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8923 TInfo->getType(),
8924 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8925 << TInfo->getTypeLoc().getSourceRange()))
8926 return ExprError();
8927
Douglas Gregor4eb75222011-07-30 06:45:27 +00008928 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00008929 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00008930 TInfo->getType()->isObjCLifetimeType()
8931 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8932 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00008933 << TInfo->getType()
8934 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00008935 }
Eli Friedman46d37c12011-07-11 21:45:59 +00008936
8937 // Check for va_arg where arguments of the given type will be promoted
8938 // (i.e. this va_arg is guaranteed to have undefined behavior).
8939 QualType PromoteType;
8940 if (TInfo->getType()->isPromotableIntegerType()) {
8941 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8942 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8943 PromoteType = QualType();
8944 }
8945 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8946 PromoteType = Context.DoubleTy;
8947 if (!PromoteType.isNull())
8948 Diag(TInfo->getTypeLoc().getBeginLoc(),
8949 diag::warn_second_parameter_to_va_arg_never_compatible)
8950 << TInfo->getType()
8951 << PromoteType
8952 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00008953 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008954
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008955 QualType T = TInfo->getType().getNonLValueExprType(Context);
8956 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008957}
8958
John McCall60d7b3a2010-08-24 06:29:42 +00008959ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008960 // The type of __null will be int or long, depending on the size of
8961 // pointers on the target.
8962 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00008963 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
8964 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008965 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00008966 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008967 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00008968 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008969 Ty = Context.LongLongTy;
8970 else {
David Blaikieb219cfc2011-09-23 05:06:16 +00008971 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008972 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008973
Sebastian Redlf53597f2009-03-15 17:47:39 +00008974 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008975}
8976
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008977static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00008978 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008979 if (!SemaRef.getLangOptions().ObjC1)
8980 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008981
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008982 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8983 if (!PT)
8984 return;
8985
8986 // Check if the destination is of type 'id'.
8987 if (!PT->isObjCIdType()) {
8988 // Check if the destination is the 'NSString' interface.
8989 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8990 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8991 return;
8992 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008993
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008994 // Strip off any parens and casts.
8995 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregor5cee1192011-07-27 05:40:30 +00008996 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008997 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008998
Douglas Gregor849b2432010-03-31 17:46:05 +00008999 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009000}
9001
Chris Lattner5cf216b2008-01-04 18:04:52 +00009002bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9003 SourceLocation Loc,
9004 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009005 Expr *SrcExpr, AssignmentAction Action,
9006 bool *Complained) {
9007 if (Complained)
9008 *Complained = false;
9009
Chris Lattner5cf216b2008-01-04 18:04:52 +00009010 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00009011 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009012 bool isInvalid = false;
9013 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00009014 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00009015 ConversionFixItGenerator ConvHints;
9016 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009017
Chris Lattner5cf216b2008-01-04 18:04:52 +00009018 switch (ConvTy) {
David Blaikieb219cfc2011-09-23 05:06:16 +00009019 default: llvm_unreachable("Unknown conversion type");
Chris Lattner5cf216b2008-01-04 18:04:52 +00009020 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009021 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009022 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00009023 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9024 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009025 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009026 case IntToPointer:
9027 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00009028 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9029 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009030 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009031 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009032 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009033 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00009034 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9035 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00009036 if (Hint.isNull() && !CheckInferredResultType) {
9037 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9038 }
9039 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009040 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009041 case IncompatiblePointerSign:
9042 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9043 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009044 case FunctionVoidPointer:
9045 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9046 break;
John McCall86c05f32011-02-01 00:10:29 +00009047 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009048 // Perform array-to-pointer decay if necessary.
9049 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9050
John McCall86c05f32011-02-01 00:10:29 +00009051 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9052 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9053 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9054 DiagKind = diag::err_typecheck_incompatible_address_space;
9055 break;
John McCallf85e1932011-06-15 23:02:42 +00009056
9057
9058 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009059 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00009060 break;
John McCall86c05f32011-02-01 00:10:29 +00009061 }
9062
9063 llvm_unreachable("unknown error case for discarding qualifiers!");
9064 // fallthrough
9065 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009066 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009067 // If the qualifiers lost were because we were applying the
9068 // (deprecated) C++ conversion from a string literal to a char*
9069 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9070 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009071 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009072 // bit of refactoring (so that the second argument is an
9073 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009074 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009075 // C++ semantics.
9076 if (getLangOptions().CPlusPlus &&
9077 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9078 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009079 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9080 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009081 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009082 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009083 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009084 case IntToBlockPointer:
9085 DiagKind = diag::err_int_to_block_pointer;
9086 break;
9087 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009088 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009089 break;
Steve Naroff39579072008-10-14 22:18:38 +00009090 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009091 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009092 // it can give a more specific diagnostic.
9093 DiagKind = diag::warn_incompatible_qualified_id;
9094 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009095 case IncompatibleVectors:
9096 DiagKind = diag::warn_incompatible_vectors;
9097 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00009098 case IncompatibleObjCWeakRef:
9099 DiagKind = diag::err_arc_weak_unavailable_assign;
9100 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009101 case Incompatible:
9102 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00009103 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9104 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009105 isInvalid = true;
9106 break;
9107 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009108
Douglas Gregord4eea832010-04-09 00:35:39 +00009109 QualType FirstType, SecondType;
9110 switch (Action) {
9111 case AA_Assigning:
9112 case AA_Initializing:
9113 // The destination type comes first.
9114 FirstType = DstType;
9115 SecondType = SrcType;
9116 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009117
Douglas Gregord4eea832010-04-09 00:35:39 +00009118 case AA_Returning:
9119 case AA_Passing:
9120 case AA_Converting:
9121 case AA_Sending:
9122 case AA_Casting:
9123 // The source type comes first.
9124 FirstType = SrcType;
9125 SecondType = DstType;
9126 break;
9127 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009128
Anna Zaks67221552011-07-28 19:51:27 +00009129 PartialDiagnostic FDiag = PDiag(DiagKind);
9130 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9131
9132 // If we can fix the conversion, suggest the FixIts.
9133 assert(ConvHints.isNull() || Hint.isNull());
9134 if (!ConvHints.isNull()) {
9135 for (llvm::SmallVector<FixItHint, 1>::iterator
9136 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
9137 HI != HE; ++HI)
9138 FDiag << *HI;
9139 } else {
9140 FDiag << Hint;
9141 }
9142 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9143
9144 Diag(Loc, FDiag);
9145
Douglas Gregor926df6c2011-06-11 01:09:30 +00009146 if (CheckInferredResultType)
9147 EmitRelatedResultTypeNote(SrcExpr);
9148
Douglas Gregora41a8c52010-04-22 00:20:18 +00009149 if (Complained)
9150 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009151 return isInvalid;
9152}
Anders Carlssone21555e2008-11-30 19:50:32 +00009153
Chris Lattner3bf68932009-04-25 21:59:05 +00009154bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009155 llvm::APSInt ICEResult;
9156 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9157 if (Result)
9158 *Result = ICEResult;
9159 return false;
9160 }
9161
Anders Carlssone21555e2008-11-30 19:50:32 +00009162 Expr::EvalResult EvalResult;
9163
Mike Stumpeed9cac2009-02-19 03:04:26 +00009164 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00009165 EvalResult.HasSideEffects) {
9166 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9167
9168 if (EvalResult.Diag) {
9169 // We only show the note if it's not the usual "invalid subexpression"
9170 // or if it's actually in a subexpression.
9171 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9172 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9173 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9174 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009175
Anders Carlssone21555e2008-11-30 19:50:32 +00009176 return true;
9177 }
9178
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009179 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9180 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00009181
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009182 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009183 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
David Blaikied6471f72011-09-25 23:23:43 +00009184 != DiagnosticsEngine::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009185 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009186
Anders Carlssone21555e2008-11-30 19:50:32 +00009187 if (Result)
9188 *Result = EvalResult.Val.getInt();
9189 return false;
9190}
Douglas Gregore0762c92009-06-19 23:52:42 +00009191
Douglas Gregor2afce722009-11-26 00:44:06 +00009192void
Mike Stump1eb44332009-09-09 15:08:12 +00009193Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009194 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +00009195 ExpressionEvaluationContextRecord(NewContext,
9196 ExprTemporaries.size(),
9197 ExprNeedsCleanups));
9198 ExprNeedsCleanups = false;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009199}
9200
Richard Trieu67e29332011-08-02 04:35:43 +00009201void Sema::PopExpressionEvaluationContext() {
Douglas Gregor2afce722009-11-26 00:44:06 +00009202 // Pop the current expression evaluation context off the stack.
9203 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9204 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009205
Douglas Gregor06d33692009-12-12 07:57:52 +00009206 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9207 if (Rec.PotentiallyReferenced) {
9208 // Mark any remaining declarations in the current position of the stack
9209 // as "referenced". If they were not meant to be referenced, semantic
9210 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009211 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00009212 I = Rec.PotentiallyReferenced->begin(),
9213 IEnd = Rec.PotentiallyReferenced->end();
9214 I != IEnd; ++I)
9215 MarkDeclarationReferenced(I->first, I->second);
9216 }
9217
9218 if (Rec.PotentiallyDiagnosed) {
9219 // Emit any pending diagnostics.
9220 for (PotentiallyEmittedDiagnostics::iterator
9221 I = Rec.PotentiallyDiagnosed->begin(),
9222 IEnd = Rec.PotentiallyDiagnosed->end();
9223 I != IEnd; ++I)
9224 Diag(I->first, I->second);
9225 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009226 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009227
9228 // When are coming out of an unevaluated context, clear out any
9229 // temporaries that we may have created as part of the evaluation of
9230 // the expression in that context: they aren't relevant because they
9231 // will never be constructed.
John McCallf85e1932011-06-15 23:02:42 +00009232 if (Rec.Context == Unevaluated) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009233 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9234 ExprTemporaries.end());
John McCallf85e1932011-06-15 23:02:42 +00009235 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9236
9237 // Otherwise, merge the contexts together.
9238 } else {
9239 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9240 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009241
9242 // Destroy the popped expression evaluation record.
9243 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009244}
Douglas Gregore0762c92009-06-19 23:52:42 +00009245
John McCallf85e1932011-06-15 23:02:42 +00009246void Sema::DiscardCleanupsInEvaluationContext() {
9247 ExprTemporaries.erase(
9248 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9249 ExprTemporaries.end());
9250 ExprNeedsCleanups = false;
9251}
9252
Douglas Gregore0762c92009-06-19 23:52:42 +00009253/// \brief Note that the given declaration was referenced in the source code.
9254///
9255/// This routine should be invoke whenever a given declaration is referenced
9256/// in the source code, and where that reference occurred. If this declaration
9257/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9258/// C99 6.9p3), then the declaration will be marked as used.
9259///
9260/// \param Loc the location where the declaration was referenced.
9261///
9262/// \param D the declaration that has been referenced by the source code.
9263void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9264 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009265
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +00009266 D->setReferenced();
9267
Douglas Gregorc070cc62010-06-17 23:14:26 +00009268 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009269 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009270
Richard Trieu67e29332011-08-02 04:35:43 +00009271 // Mark a parameter or variable declaration "used", regardless of whether
9272 // we're in a template or not. The reason for this is that unevaluated
9273 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9274 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009275 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009276 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009277 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009278 return;
9279 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009280
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009281 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9282 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009283
Douglas Gregore0762c92009-06-19 23:52:42 +00009284 // Do not mark anything as "used" within a dependent context; wait for
9285 // an instantiation.
9286 if (CurContext->isDependentContext())
9287 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009288
Douglas Gregor2afce722009-11-26 00:44:06 +00009289 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009290 case Unevaluated:
9291 // We are in an expression that is not potentially evaluated; do nothing.
9292 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009293
Douglas Gregorac7610d2009-06-22 20:57:11 +00009294 case PotentiallyEvaluated:
9295 // We are in a potentially-evaluated expression, so this declaration is
9296 // "used"; handle this below.
9297 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009298
Douglas Gregorac7610d2009-06-22 20:57:11 +00009299 case PotentiallyPotentiallyEvaluated:
9300 // We are in an expression that may be potentially evaluated; queue this
9301 // declaration reference until we know whether the expression is
9302 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009303 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009304 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009305
9306 case PotentiallyEvaluatedIfUsed:
9307 // Referenced declarations will only be used if the construct in the
9308 // containing expression is used.
9309 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009310 }
Mike Stump1eb44332009-09-09 15:08:12 +00009311
Douglas Gregore0762c92009-06-19 23:52:42 +00009312 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009313 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009314 if (Constructor->isDefaulted()) {
9315 if (Constructor->isDefaultConstructor()) {
9316 if (Constructor->isTrivial())
9317 return;
9318 if (!Constructor->isUsed(false))
9319 DefineImplicitDefaultConstructor(Loc, Constructor);
9320 } else if (Constructor->isCopyConstructor()) {
9321 if (!Constructor->isUsed(false))
9322 DefineImplicitCopyConstructor(Loc, Constructor);
9323 } else if (Constructor->isMoveConstructor()) {
9324 if (!Constructor->isUsed(false))
9325 DefineImplicitMoveConstructor(Loc, Constructor);
9326 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009327 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009328
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009329 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009330 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00009331 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009332 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009333 if (Destructor->isVirtual())
9334 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009335 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Sean Hunt2b188082011-05-14 05:23:28 +00009336 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009337 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009338 if (!MethodDecl->isUsed(false)) {
9339 if (MethodDecl->isCopyAssignmentOperator())
9340 DefineImplicitCopyAssignment(Loc, MethodDecl);
9341 else
9342 DefineImplicitMoveAssignment(Loc, MethodDecl);
9343 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009344 } else if (MethodDecl->isVirtual())
9345 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009346 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009347 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +00009348 // Recursive functions should be marked when used from another function.
9349 if (CurContext == Function) return;
9350
Mike Stump1eb44332009-09-09 15:08:12 +00009351 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009352 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009353 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009354 bool AlreadyInstantiated = false;
9355 if (FunctionTemplateSpecializationInfo *SpecInfo
9356 = Function->getTemplateSpecializationInfo()) {
9357 if (SpecInfo->getPointOfInstantiation().isInvalid())
9358 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009359 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009360 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009361 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009362 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009363 = Function->getMemberSpecializationInfo()) {
9364 if (MSInfo->getPointOfInstantiation().isInvalid())
9365 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009366 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009367 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009368 AlreadyInstantiated = true;
9369 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009370
Douglas Gregor60406be2010-01-16 22:29:39 +00009371 if (!AlreadyInstantiated) {
9372 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9373 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9374 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9375 Loc));
9376 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00009377 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00009378 }
John McCall15e310a2011-02-19 02:53:41 +00009379 } else {
9380 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +00009381 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9382 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00009383 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00009384 MarkDeclarationReferenced(Loc, *i);
9385 }
John McCall15e310a2011-02-19 02:53:41 +00009386 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009387
John McCall15e310a2011-02-19 02:53:41 +00009388 // Keep track of used but undefined functions.
9389 if (!Function->isPure() && !Function->hasBody() &&
9390 Function->getLinkage() != ExternalLinkage) {
9391 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9392 if (old.isInvalid()) old = Loc;
9393 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00009394
John McCall15e310a2011-02-19 02:53:41 +00009395 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +00009396 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009397 }
Mike Stump1eb44332009-09-09 15:08:12 +00009398
Douglas Gregore0762c92009-06-19 23:52:42 +00009399 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00009400 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00009401 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009402 Var->getInstantiatedFromStaticDataMember()) {
9403 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9404 assert(MSInfo && "Missing member specialization information?");
9405 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9406 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9407 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redlf79a7192011-04-29 08:19:30 +00009408 // This is a modification of an existing AST node. Notify listeners.
9409 if (ASTMutationListener *L = getASTMutationListener())
9410 L->StaticDataMemberInstantiated(Var);
Chandler Carruth62c78d52010-08-25 08:44:16 +00009411 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009412 }
9413 }
Mike Stump1eb44332009-09-09 15:08:12 +00009414
John McCall77efc682011-02-21 19:25:48 +00009415 // Keep track of used but undefined variables. We make a hole in
9416 // the warning for static const data members with in-line
9417 // initializers.
John McCall15e310a2011-02-19 02:53:41 +00009418 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall77efc682011-02-21 19:25:48 +00009419 && Var->getLinkage() != ExternalLinkage
9420 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall15e310a2011-02-19 02:53:41 +00009421 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9422 if (old.isInvalid()) old = Loc;
9423 }
Douglas Gregor7caa6822009-07-24 20:34:43 +00009424
Douglas Gregore0762c92009-06-19 23:52:42 +00009425 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00009426 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00009427 }
Douglas Gregore0762c92009-06-19 23:52:42 +00009428}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009429
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009430namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009431 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009432 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009433 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009434 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9435 Sema &S;
9436 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009437
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009438 public:
9439 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009440
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009441 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009442
9443 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9444 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009445 };
9446}
9447
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009448bool MarkReferencedDecls::TraverseTemplateArgument(
9449 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009450 if (Arg.getKind() == TemplateArgument::Declaration) {
9451 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9452 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009453
9454 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009455}
9456
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009457bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009458 if (ClassTemplateSpecializationDecl *Spec
9459 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9460 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +00009461 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009462 }
9463
Chandler Carruthe3e210c2010-06-10 10:31:57 +00009464 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009465}
9466
9467void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9468 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009469 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009470}
9471
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009472namespace {
9473 /// \brief Helper class that marks all of the declarations referenced by
9474 /// potentially-evaluated subexpressions as "referenced".
9475 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9476 Sema &S;
9477
9478 public:
9479 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9480
9481 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9482
9483 void VisitDeclRefExpr(DeclRefExpr *E) {
9484 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9485 }
9486
9487 void VisitMemberExpr(MemberExpr *E) {
9488 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009489 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009490 }
9491
9492 void VisitCXXNewExpr(CXXNewExpr *E) {
9493 if (E->getConstructor())
9494 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9495 if (E->getOperatorNew())
9496 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9497 if (E->getOperatorDelete())
9498 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009499 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009500 }
9501
9502 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9503 if (E->getOperatorDelete())
9504 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +00009505 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9506 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9507 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9508 S.MarkDeclarationReferenced(E->getLocStart(),
9509 S.LookupDestructor(Record));
9510 }
9511
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009512 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009513 }
9514
9515 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9516 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009517 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009518 }
9519
9520 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9521 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9522 }
Douglas Gregor102ff972010-10-19 17:17:35 +00009523
9524 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9525 Visit(E->getExpr());
9526 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009527 };
9528}
9529
9530/// \brief Mark any declarations that appear within this expression or any
9531/// potentially-evaluated subexpressions as "referenced".
9532void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9533 EvaluatedExprMarker(*this).Visit(E);
9534}
9535
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009536/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9537/// of the program being compiled.
9538///
9539/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009540/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009541/// possibility that the code will actually be executable. Code in sizeof()
9542/// expressions, code used only during overload resolution, etc., are not
9543/// potentially evaluated. This routine will suppress such diagnostics or,
9544/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009545/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009546/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009547///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009548/// This routine should be used for all diagnostics that describe the run-time
9549/// behavior of a program, such as passing a non-POD value through an ellipsis.
9550/// Failure to do so will likely result in spurious diagnostics or failures
9551/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +00009552bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009553 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +00009554 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009555 case Unevaluated:
9556 // The argument will never be evaluated, so don't complain.
9557 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009558
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009559 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009560 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +00009561 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00009562 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +00009563 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +00009564 }
9565 else
9566 Diag(Loc, PD);
9567
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009568 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009569
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009570 case PotentiallyPotentiallyEvaluated:
9571 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9572 break;
9573 }
9574
9575 return false;
9576}
9577
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009578bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9579 CallExpr *CE, FunctionDecl *FD) {
9580 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9581 return false;
9582
9583 PartialDiagnostic Note =
9584 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9585 << FD->getDeclName() : PDiag();
9586 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009587
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009588 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009589 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009590 PDiag(diag::err_call_function_incomplete_return)
9591 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009592 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009593 << CE->getSourceRange(),
9594 std::make_pair(NoteLoc, Note)))
9595 return true;
9596
9597 return false;
9598}
9599
Douglas Gregor92c3a042011-01-19 16:50:08 +00009600// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +00009601// will prevent this condition from triggering, which is what we want.
9602void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9603 SourceLocation Loc;
9604
John McCalla52ef082009-11-11 02:41:58 +00009605 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +00009606 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +00009607
Chandler Carruthb33c19f2011-08-16 22:30:10 +00009608 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +00009609 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +00009610 return;
9611
Douglas Gregor92c3a042011-01-19 16:50:08 +00009612 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9613
John McCallc8d8ac52009-11-12 00:06:05 +00009614 // Greylist some idioms by putting them into a warning subcategory.
9615 if (ObjCMessageExpr *ME
9616 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9617 Selector Sel = ME->getSelector();
9618
John McCallc8d8ac52009-11-12 00:06:05 +00009619 // self = [<foo> init...]
Douglas Gregorc737acb2011-09-27 16:10:05 +00009620 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +00009621 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9622
9623 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +00009624 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +00009625 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9626 }
John McCalla52ef082009-11-11 02:41:58 +00009627
John McCall5a881bb2009-10-12 21:59:07 +00009628 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +00009629 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +00009630 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +00009631 return;
9632
Douglas Gregor92c3a042011-01-19 16:50:08 +00009633 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +00009634 Loc = Op->getOperatorLoc();
9635 } else {
9636 // Not an assignment.
9637 return;
9638 }
9639
Douglas Gregor55b38842010-04-14 16:09:52 +00009640 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +00009641
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009642 SourceLocation Open = E->getSourceRange().getBegin();
9643 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9644 Diag(Loc, diag::note_condition_assign_silence)
9645 << FixItHint::CreateInsertion(Open, "(")
9646 << FixItHint::CreateInsertion(Close, ")");
9647
Douglas Gregor92c3a042011-01-19 16:50:08 +00009648 if (IsOrAssign)
9649 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9650 << FixItHint::CreateReplacement(Loc, "!=");
9651 else
9652 Diag(Loc, diag::note_condition_assign_to_comparison)
9653 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +00009654}
9655
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009656/// \brief Redundant parentheses over an equality comparison can indicate
9657/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +00009658void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009659 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +00009660 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009661 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9662 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +00009663 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00009664 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +00009665 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009666
Richard Trieuccd891a2011-09-09 01:45:06 +00009667 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009668
9669 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +00009670 if (opE->getOpcode() == BO_EQ &&
9671 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9672 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009673 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +00009674
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009675 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009676 Diag(Loc, diag::note_equality_comparison_silence)
Richard Trieuccd891a2011-09-09 01:45:06 +00009677 << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin())
9678 << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009679 Diag(Loc, diag::note_equality_comparison_to_assign)
9680 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009681 }
9682}
9683
John Wiegley429bb272011-04-08 18:41:53 +00009684ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +00009685 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009686 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9687 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +00009688
John McCall864c0412011-04-26 20:42:42 +00009689 ExprResult result = CheckPlaceholderExpr(E);
9690 if (result.isInvalid()) return ExprError();
9691 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00009692
John McCall864c0412011-04-26 20:42:42 +00009693 if (!E->isTypeDependent()) {
John McCallf6a16482010-12-04 03:47:34 +00009694 if (getLangOptions().CPlusPlus)
9695 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9696
John Wiegley429bb272011-04-08 18:41:53 +00009697 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9698 if (ERes.isInvalid())
9699 return ExprError();
9700 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +00009701
9702 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +00009703 if (!T->isScalarType()) { // C99 6.8.4.1p1
9704 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9705 << T << E->getSourceRange();
9706 return ExprError();
9707 }
John McCall5a881bb2009-10-12 21:59:07 +00009708 }
9709
John Wiegley429bb272011-04-08 18:41:53 +00009710 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +00009711}
Douglas Gregor586596f2010-05-06 17:25:47 +00009712
John McCall60d7b3a2010-08-24 06:29:42 +00009713ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009714 Expr *SubExpr) {
9715 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +00009716 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009717
Richard Trieuccd891a2011-09-09 01:45:06 +00009718 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +00009719}
John McCall2a984ca2010-10-12 00:20:44 +00009720
John McCall1de4d4e2011-04-07 08:22:57 +00009721namespace {
John McCall755d8492011-04-12 00:42:48 +00009722 /// A visitor for rebuilding a call to an __unknown_any expression
9723 /// to have an appropriate type.
9724 struct RebuildUnknownAnyFunction
9725 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9726
9727 Sema &S;
9728
9729 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9730
9731 ExprResult VisitStmt(Stmt *S) {
9732 llvm_unreachable("unexpected statement!");
9733 return ExprError();
9734 }
9735
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009736 ExprResult VisitExpr(Expr *E) {
9737 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
9738 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +00009739 return ExprError();
9740 }
9741
9742 /// Rebuild an expression which simply semantically wraps another
9743 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009744 template <class T> ExprResult rebuildSugarExpr(T *E) {
9745 ExprResult SubResult = Visit(E->getSubExpr());
9746 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +00009747
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009748 Expr *SubExpr = SubResult.take();
9749 E->setSubExpr(SubExpr);
9750 E->setType(SubExpr->getType());
9751 E->setValueKind(SubExpr->getValueKind());
9752 assert(E->getObjectKind() == OK_Ordinary);
9753 return E;
John McCall755d8492011-04-12 00:42:48 +00009754 }
9755
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009756 ExprResult VisitParenExpr(ParenExpr *E) {
9757 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +00009758 }
9759
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009760 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9761 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +00009762 }
9763
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009764 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9765 ExprResult SubResult = Visit(E->getSubExpr());
9766 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +00009767
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009768 Expr *SubExpr = SubResult.take();
9769 E->setSubExpr(SubExpr);
9770 E->setType(S.Context.getPointerType(SubExpr->getType()));
9771 assert(E->getValueKind() == VK_RValue);
9772 assert(E->getObjectKind() == OK_Ordinary);
9773 return E;
John McCall755d8492011-04-12 00:42:48 +00009774 }
9775
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009776 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
9777 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +00009778
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009779 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +00009780
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009781 assert(E->getValueKind() == VK_RValue);
John McCall755d8492011-04-12 00:42:48 +00009782 if (S.getLangOptions().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009783 !(isa<CXXMethodDecl>(VD) &&
9784 cast<CXXMethodDecl>(VD)->isInstance()))
9785 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +00009786
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009787 return E;
John McCall755d8492011-04-12 00:42:48 +00009788 }
9789
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009790 ExprResult VisitMemberExpr(MemberExpr *E) {
9791 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +00009792 }
9793
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009794 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9795 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +00009796 }
9797 };
9798}
9799
9800/// Given a function expression of unknown-any type, try to rebuild it
9801/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009802static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
9803 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
9804 if (Result.isInvalid()) return ExprError();
9805 return S.DefaultFunctionArrayConversion(Result.take());
John McCall755d8492011-04-12 00:42:48 +00009806}
9807
9808namespace {
John McCall379b5152011-04-11 07:02:50 +00009809 /// A visitor for rebuilding an expression of type __unknown_anytype
9810 /// into one which resolves the type directly on the referring
9811 /// expression. Strict preservation of the original source
9812 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +00009813 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +00009814 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +00009815
9816 Sema &S;
9817
9818 /// The current destination type.
9819 QualType DestType;
9820
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009821 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
9822 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +00009823
John McCalla5fc4722011-04-09 22:50:59 +00009824 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +00009825 llvm_unreachable("unexpected statement!");
John McCalla5fc4722011-04-09 22:50:59 +00009826 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009827 }
9828
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009829 ExprResult VisitExpr(Expr *E) {
9830 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9831 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +00009832 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009833 }
9834
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009835 ExprResult VisitCallExpr(CallExpr *E);
9836 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +00009837
John McCalla5fc4722011-04-09 22:50:59 +00009838 /// Rebuild an expression which simply semantically wraps another
9839 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009840 template <class T> ExprResult rebuildSugarExpr(T *E) {
9841 ExprResult SubResult = Visit(E->getSubExpr());
9842 if (SubResult.isInvalid()) return ExprError();
9843 Expr *SubExpr = SubResult.take();
9844 E->setSubExpr(SubExpr);
9845 E->setType(SubExpr->getType());
9846 E->setValueKind(SubExpr->getValueKind());
9847 assert(E->getObjectKind() == OK_Ordinary);
9848 return E;
John McCalla5fc4722011-04-09 22:50:59 +00009849 }
John McCall1de4d4e2011-04-07 08:22:57 +00009850
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009851 ExprResult VisitParenExpr(ParenExpr *E) {
9852 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +00009853 }
9854
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009855 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9856 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +00009857 }
9858
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009859 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9860 const PointerType *Ptr = DestType->getAs<PointerType>();
9861 if (!Ptr) {
9862 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
9863 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +00009864 return ExprError();
9865 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009866 assert(E->getValueKind() == VK_RValue);
9867 assert(E->getObjectKind() == OK_Ordinary);
9868 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +00009869
9870 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009871 DestType = Ptr->getPointeeType();
9872 ExprResult SubResult = Visit(E->getSubExpr());
9873 if (SubResult.isInvalid()) return ExprError();
9874 E->setSubExpr(SubResult.take());
9875 return E;
John McCall755d8492011-04-12 00:42:48 +00009876 }
9877
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009878 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +00009879
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009880 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +00009881
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009882 ExprResult VisitMemberExpr(MemberExpr *E) {
9883 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +00009884 }
John McCalla5fc4722011-04-09 22:50:59 +00009885
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009886 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9887 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +00009888 }
9889 };
9890}
9891
John McCall379b5152011-04-11 07:02:50 +00009892/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009893ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
9894 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +00009895
9896 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +00009897 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +00009898 FK_FunctionPointer,
9899 FK_BlockPointer
9900 };
9901
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009902 FnKind Kind;
9903 QualType CalleeType = CalleeExpr->getType();
9904 if (CalleeType == S.Context.BoundMemberTy) {
9905 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
9906 Kind = FK_MemberFunction;
9907 CalleeType = Expr::findBoundMemberType(CalleeExpr);
9908 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
9909 CalleeType = Ptr->getPointeeType();
9910 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +00009911 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009912 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
9913 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +00009914 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009915 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +00009916
9917 // Verify that this is a legal result type of a function.
9918 if (DestType->isArrayType() || DestType->isFunctionType()) {
9919 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009920 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +00009921 diagID = diag::err_block_returning_array_function;
9922
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009923 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +00009924 << DestType->isFunctionType() << DestType;
9925 return ExprError();
9926 }
9927
9928 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009929 E->setType(DestType.getNonLValueExprType(S.Context));
9930 E->setValueKind(Expr::getValueKindForType(DestType));
9931 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +00009932
9933 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009934 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall379b5152011-04-11 07:02:50 +00009935 DestType = S.Context.getFunctionType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009936 Proto->arg_type_begin(),
9937 Proto->getNumArgs(),
9938 Proto->getExtProtoInfo());
John McCall379b5152011-04-11 07:02:50 +00009939 else
9940 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009941 FnType->getExtInfo());
John McCall379b5152011-04-11 07:02:50 +00009942
9943 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009944 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +00009945 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +00009946 // Nothing to do.
9947 break;
9948
9949 case FK_FunctionPointer:
9950 DestType = S.Context.getPointerType(DestType);
9951 break;
9952
9953 case FK_BlockPointer:
9954 DestType = S.Context.getBlockPointerType(DestType);
9955 break;
9956 }
9957
9958 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009959 ExprResult CalleeResult = Visit(CalleeExpr);
9960 if (!CalleeResult.isUsable()) return ExprError();
9961 E->setCallee(CalleeResult.take());
John McCall379b5152011-04-11 07:02:50 +00009962
9963 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009964 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +00009965}
9966
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009967ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +00009968 // Verify that this is a legal result type of a call.
9969 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009970 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +00009971 << DestType->isFunctionType() << DestType;
9972 return ExprError();
John McCall379b5152011-04-11 07:02:50 +00009973 }
9974
John McCall48218c62011-07-13 17:56:40 +00009975 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009976 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
9977 assert(Method->getResultType() == S.Context.UnknownAnyTy);
9978 Method->setResultType(DestType);
John McCall48218c62011-07-13 17:56:40 +00009979 }
John McCall755d8492011-04-12 00:42:48 +00009980
John McCall379b5152011-04-11 07:02:50 +00009981 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009982 E->setType(DestType.getNonReferenceType());
9983 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +00009984
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009985 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +00009986}
9987
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009988ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +00009989 // The only case we should ever see here is a function-to-pointer decay.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009990 assert(E->getCastKind() == CK_FunctionToPointerDecay);
9991 assert(E->getValueKind() == VK_RValue);
9992 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +00009993
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009994 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +00009995
John McCall379b5152011-04-11 07:02:50 +00009996 // Rebuild the sub-expression as the pointee (function) type.
9997 DestType = DestType->castAs<PointerType>()->getPointeeType();
9998
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009999 ExprResult Result = Visit(E->getSubExpr());
10000 if (!Result.isUsable()) return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010001
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010002 E->setSubExpr(Result.take());
10003 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000010004}
10005
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010006ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
10007 ExprValueKind ValueKind = VK_LValue;
10008 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +000010009
10010 // We know how to make this work for certain kinds of decls:
10011
10012 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010013 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
10014 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
10015 DestType = Ptr->getPointeeType();
10016 ExprResult Result = resolveDecl(E, VD);
10017 if (Result.isInvalid()) return ExprError();
10018 return S.ImpCastExprToType(Result.take(), Type,
John McCalla19950e2011-08-10 04:12:23 +000010019 CK_FunctionToPointerDecay, VK_RValue);
10020 }
10021
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010022 if (!Type->isFunctionType()) {
10023 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
10024 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +000010025 return ExprError();
10026 }
John McCall379b5152011-04-11 07:02:50 +000010027
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010028 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
10029 if (MD->isInstance()) {
10030 ValueKind = VK_RValue;
10031 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +000010032 }
10033
John McCall379b5152011-04-11 07:02:50 +000010034 // Function references aren't l-values in C.
10035 if (!S.getLangOptions().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010036 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +000010037
10038 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010039 } else if (isa<VarDecl>(VD)) {
10040 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
10041 Type = RefTy->getPointeeType();
10042 } else if (Type->isFunctionType()) {
10043 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
10044 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000010045 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010046 }
10047
10048 // - nothing else
10049 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010050 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10051 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000010052 return ExprError();
10053 }
10054
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010055 VD->setType(DestType);
10056 E->setType(Type);
10057 E->setValueKind(ValueKind);
10058 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000010059}
10060
John McCall1de4d4e2011-04-07 08:22:57 +000010061/// Check a cast of an unknown-any type. We intentionally only
10062/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +000010063ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
10064 Expr *CastExpr, CastKind &CastKind,
10065 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000010066 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000010067 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000010068 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010069
Richard Trieuccd891a2011-09-09 01:45:06 +000010070 CastExpr = result.take();
10071 VK = CastExpr->getValueKind();
10072 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000010073
Richard Trieuccd891a2011-09-09 01:45:06 +000010074 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000010075}
10076
Richard Trieuccd891a2011-09-09 01:45:06 +000010077static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
10078 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000010079 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000010080 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000010081 E = E->IgnoreParenImpCasts();
10082 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
10083 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000010084 diagID = diag::err_uncasted_call_of_unknown_any;
10085 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000010086 break;
John McCall379b5152011-04-11 07:02:50 +000010087 }
John McCall1de4d4e2011-04-07 08:22:57 +000010088 }
10089
John McCall379b5152011-04-11 07:02:50 +000010090 SourceLocation loc;
10091 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000010092 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000010093 loc = ref->getLocation();
10094 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000010095 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000010096 loc = mem->getMemberLoc();
10097 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000010098 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000010099 diagID = diag::err_uncasted_call_of_unknown_any;
10100 loc = msg->getSelectorLoc();
10101 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000010102 if (!d) {
10103 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
10104 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
10105 << orig->getSourceRange();
10106 return ExprError();
10107 }
John McCall379b5152011-04-11 07:02:50 +000010108 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000010109 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10110 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000010111 return ExprError();
10112 }
10113
10114 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000010115
10116 // Never recoverable.
10117 return ExprError();
10118}
10119
John McCall2a984ca2010-10-12 00:20:44 +000010120/// Check for operands with placeholder types and complain if found.
10121/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000010122ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall1de4d4e2011-04-07 08:22:57 +000010123 // Placeholder types are always *exactly* the appropriate builtin type.
10124 QualType type = E->getType();
John McCall2a984ca2010-10-12 00:20:44 +000010125
John McCall1de4d4e2011-04-07 08:22:57 +000010126 // Overloaded expressions.
10127 if (type == Context.OverloadTy)
10128 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregordb2eae62011-03-16 19:16:25 +000010129 E->getSourceRange(),
John McCall1de4d4e2011-04-07 08:22:57 +000010130 QualType(),
10131 diag::err_ovl_unresolvable);
10132
John McCall864c0412011-04-26 20:42:42 +000010133 // Bound member functions.
10134 if (type == Context.BoundMemberTy) {
10135 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10136 << E->getSourceRange();
10137 return ExprError();
10138 }
10139
John McCall1de4d4e2011-04-07 08:22:57 +000010140 // Expressions of unknown type.
10141 if (type == Context.UnknownAnyTy)
10142 return diagnoseUnknownAnyExpr(*this, E);
10143
10144 assert(!type->isPlaceholderType());
10145 return Owned(E);
John McCall2a984ca2010-10-12 00:20:44 +000010146}
Richard Trieubb9b80c2011-04-21 21:44:26 +000010147
Richard Trieuccd891a2011-09-09 01:45:06 +000010148bool Sema::CheckCaseExpression(Expr *E) {
10149 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000010150 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000010151 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
10152 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000010153 return false;
10154}