blob: 2706ae43daddd0ddc9f7daad360d95a615b20e16 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000015#include "clang/Sema/DelayedDiagnostic.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000018#include "clang/Sema/ScopeInfo.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000019#include "clang/Sema/AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000020#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000021#include "clang/AST/ASTConsumer.h"
Sebastian Redl2ac2c722011-04-29 08:19:30 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregord1702062010-04-29 00:18:15 +000023#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000025#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000027#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000028#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000029#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000030#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000031#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000032#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000033#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000034#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000035#include "clang/Lex/LiteralSupport.h"
36#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000037#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/Designator.h"
39#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000040#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000041#include "clang/Sema/ParsedTemplate.h"
Anna Zaks3b402712011-07-28 19:51:27 +000042#include "clang/Sema/SemaFixItUtils.h"
John McCallde6836a2010-08-24 07:21:54 +000043#include "clang/Sema/Template.h"
Eli Friedman456f0182012-01-20 01:26:23 +000044#include "TreeTransform.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000045using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000046using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000047
Sebastian Redlb49c46c2011-09-24 17:48:00 +000048/// \brief Determine whether the use of this declaration is valid, without
49/// emitting diagnostics.
50bool Sema::CanUseDecl(NamedDecl *D) {
51 // See if this is an auto-typed variable whose initializer we are parsing.
52 if (ParsingInitForAutoVars.count(D))
53 return false;
54
55 // See if this is a deleted function.
56 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
57 if (FD->isDeleted())
58 return false;
59 }
Sebastian Redl5999aec2011-10-16 18:19:16 +000060
61 // See if this function is unavailable.
62 if (D->getAvailability() == AR_Unavailable &&
63 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
64 return false;
65
Sebastian Redlb49c46c2011-09-24 17:48:00 +000066 return true;
67}
David Chisnall9f57c292009-08-17 16:35:33 +000068
Ted Kremenek6eb25622012-02-10 02:45:47 +000069static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000070 NamedDecl *D, SourceLocation Loc,
71 const ObjCInterfaceDecl *UnknownObjCClass) {
72 // See if this declaration is unavailable or deprecated.
73 std::string Message;
74 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian25d09c22011-11-28 19:45:58 +000075 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
76 if (Result == AR_Available) {
77 const DeclContext *DC = ECD->getDeclContext();
78 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
79 Result = TheEnumDecl->getAvailability(&Message);
80 }
81
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000082 switch (Result) {
83 case AR_Available:
84 case AR_NotYetIntroduced:
85 break;
86
87 case AR_Deprecated:
Ted Kremenek6eb25622012-02-10 02:45:47 +000088 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000089 break;
90
91 case AR_Unavailable:
Ted Kremenek6eb25622012-02-10 02:45:47 +000092 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000093 if (Message.empty()) {
94 if (!UnknownObjCClass)
Ted Kremenek6eb25622012-02-10 02:45:47 +000095 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000096 else
Ted Kremenek6eb25622012-02-10 02:45:47 +000097 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000098 << D->getDeclName();
99 }
100 else
Ted Kremenek6eb25622012-02-10 02:45:47 +0000101 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000102 << D->getDeclName() << Message;
Ted Kremenek6eb25622012-02-10 02:45:47 +0000103 S.Diag(D->getLocation(), diag::note_unavailable_here)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000104 << isa<FunctionDecl>(D) << false;
105 }
106 break;
107 }
108 return Result;
109}
110
Richard Smith852265f2012-03-30 20:53:28 +0000111/// \brief Emit a note explaining that this function is deleted or unavailable.
112void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
113 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
114
Richard Smith6f1e2c62012-04-02 20:59:25 +0000115 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
116 // If the method was explicitly defaulted, point at that declaration.
117 if (!Method->isImplicit())
118 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
119
120 // Try to diagnose why this special member function was implicitly
121 // deleted. This might fail, if that reason no longer applies.
Richard Smith852265f2012-03-30 20:53:28 +0000122 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +0000123 if (CSM != CXXInvalid)
124 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
125
126 return;
Richard Smith852265f2012-03-30 20:53:28 +0000127 }
128
129 Diag(Decl->getLocation(), diag::note_unavailable_here)
130 << 1 << Decl->isDeleted();
131}
132
Jordan Rose28cd12f2012-06-18 22:09:19 +0000133/// \brief Determine whether a FunctionDecl was ever declared with an
134/// explicit storage class.
135static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
136 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
137 E = D->redecls_end();
138 I != E; ++I) {
139 if (I->getStorageClassAsWritten() != SC_None)
140 return true;
141 }
142 return false;
143}
144
145/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rosede9e9762012-06-20 18:50:06 +0000146/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose28cd12f2012-06-18 22:09:19 +0000147///
Jordan Rose28cd12f2012-06-18 22:09:19 +0000148/// This is only a warning because we used to silently accept this code, but
Jordan Rosede9e9762012-06-20 18:50:06 +0000149/// in many cases it will not behave correctly. This is not enabled in C++ mode
150/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
151/// and so while there may still be user mistakes, most of the time we can't
152/// prove that there are errors.
Jordan Rose28cd12f2012-06-18 22:09:19 +0000153static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
154 const NamedDecl *D,
155 SourceLocation Loc) {
Jordan Rosede9e9762012-06-20 18:50:06 +0000156 // This is disabled under C++; there are too many ways for this to fire in
157 // contexts where the warning is a false positive, or where it is technically
158 // correct but benign.
159 if (S.getLangOpts().CPlusPlus)
160 return;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000161
162 // Check if this is an inlined function or method.
163 FunctionDecl *Current = S.getCurFunctionDecl();
164 if (!Current)
165 return;
166 if (!Current->isInlined())
167 return;
168 if (Current->getLinkage() != ExternalLinkage)
169 return;
170
171 // Check if the decl has internal linkage.
Jordan Rosede9e9762012-06-20 18:50:06 +0000172 if (D->getLinkage() != InternalLinkage)
Jordan Rose28cd12f2012-06-18 22:09:19 +0000173 return;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000174
Jordan Rose815fe262012-06-21 05:54:50 +0000175 // Downgrade from ExtWarn to Extension if
176 // (1) the supposedly external inline function is in the main file,
177 // and probably won't be included anywhere else.
178 // (2) the thing we're referencing is a pure function.
179 // (3) the thing we're referencing is another inline function.
180 // This last can give us false negatives, but it's better than warning on
181 // wrappers for simple C library functions.
182 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
183 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
184 if (!DowngradeWarning && UsedFn)
185 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
186
187 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
188 : diag::warn_internal_in_extern_inline)
189 << /*IsVar=*/!UsedFn << D;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000190
191 // Suggest "static" on the inline function, if possible.
Jordan Rosede9e9762012-06-20 18:50:06 +0000192 if (!hasAnyExplicitStorageClass(Current)) {
Jordan Rose28cd12f2012-06-18 22:09:19 +0000193 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
194 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
195 S.Diag(DeclBegin, diag::note_convert_inline_to_static)
196 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
197 }
198
199 S.Diag(D->getCanonicalDecl()->getLocation(),
200 diag::note_internal_decl_declared_here)
201 << D;
202}
203
Douglas Gregor171c45a2009-02-18 21:56:37 +0000204/// \brief Determine whether the use of this declaration is valid, and
205/// emit any corresponding diagnostics.
206///
207/// This routine diagnoses various problems with referencing
208/// declarations that can occur when using a declaration. For example,
209/// it might warn if a deprecated or unavailable declaration is being
210/// used, or produce an error (and return true) if a C++0x deleted
211/// function is being used.
212///
213/// \returns true if there was an error (this declaration cannot be
214/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +0000215///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +0000216bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000217 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000218 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000219 // If there were any diagnostics suppressed by template argument deduction,
220 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000221 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000222 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
223 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000224 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000225 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
226 Diag(Suppressed[I].first, Suppressed[I].second);
227
228 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000229 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000230 // entry from the table, because we want to avoid ever emitting these
231 // diagnostics again.
232 Suppressed.clear();
233 }
234 }
235
Richard Smith30482bc2011-02-20 03:19:35 +0000236 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +0000237 if (ParsingInitForAutoVars.count(D)) {
238 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
239 << D->getDeclName();
240 return true;
Richard Smith30482bc2011-02-20 03:19:35 +0000241 }
242
Douglas Gregor171c45a2009-02-18 21:56:37 +0000243 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +0000244 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000245 if (FD->isDeleted()) {
246 Diag(Loc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +0000247 NoteDeletedFunction(FD);
Douglas Gregor171c45a2009-02-18 21:56:37 +0000248 return true;
249 }
Douglas Gregorde681d42009-02-24 04:26:15 +0000250 }
Ted Kremenek6eb25622012-02-10 02:45:47 +0000251 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000252
Anders Carlsson73067a02010-10-22 23:37:08 +0000253 // Warn if this is used but marked unused.
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000254 if (D->hasAttr<UnusedAttr>())
Anders Carlsson73067a02010-10-22 23:37:08 +0000255 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
Jordan Rose2684c682012-06-15 18:19:48 +0000256
Jordan Rose28cd12f2012-06-18 22:09:19 +0000257 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose2684c682012-06-15 18:19:48 +0000258
Douglas Gregor171c45a2009-02-18 21:56:37 +0000259 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000260}
261
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000262/// \brief Retrieve the message suffix that should be added to a
263/// diagnostic complaining about the given function being deleted or
264/// unavailable.
265std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
266 // FIXME: C++0x implicitly-deleted special member functions could be
267 // detected here so that we could improve diagnostics to say, e.g.,
268 // "base class 'A' had a deleted copy constructor".
269 if (FD->isDeleted())
270 return std::string();
271
272 std::string Message;
273 if (FD->getAvailability(&Message))
274 return ": " + Message;
275
276 return std::string();
277}
278
John McCallb46f2872011-09-09 07:56:05 +0000279/// DiagnoseSentinelCalls - This routine checks whether a call or
280/// message-send is to a declaration with the sentinel attribute, and
281/// if so, it checks that the requirements of the sentinel are
282/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000283void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCallb46f2872011-09-09 07:56:05 +0000284 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000285 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000286 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000287 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000288
John McCallb46f2872011-09-09 07:56:05 +0000289 // The number of formal parameters of the declaration.
290 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000291
John McCallb46f2872011-09-09 07:56:05 +0000292 // The kind of declaration. This is also an index into a %select in
293 // the diagnostic.
294 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
295
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000296 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000297 numFormalParams = MD->param_size();
298 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000299 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000300 numFormalParams = FD->param_size();
301 calleeType = CT_Function;
302 } else if (isa<VarDecl>(D)) {
303 QualType type = cast<ValueDecl>(D)->getType();
304 const FunctionType *fn = 0;
305 if (const PointerType *ptr = type->getAs<PointerType>()) {
306 fn = ptr->getPointeeType()->getAs<FunctionType>();
307 if (!fn) return;
308 calleeType = CT_Function;
309 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
310 fn = ptr->getPointeeType()->castAs<FunctionType>();
311 calleeType = CT_Block;
312 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000313 return;
John McCallb46f2872011-09-09 07:56:05 +0000314 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000315
John McCallb46f2872011-09-09 07:56:05 +0000316 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
317 numFormalParams = proto->getNumArgs();
318 } else {
319 numFormalParams = 0;
320 }
321 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000322 return;
323 }
John McCallb46f2872011-09-09 07:56:05 +0000324
325 // "nullPos" is the number of formal parameters at the end which
326 // effectively count as part of the variadic arguments. This is
327 // useful if you would prefer to not have *any* formal parameters,
328 // but the language forces you to have at least one.
329 unsigned nullPos = attr->getNullPos();
330 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
331 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
332
333 // The number of arguments which should follow the sentinel.
334 unsigned numArgsAfterSentinel = attr->getSentinel();
335
336 // If there aren't enough arguments for all the formal parameters,
337 // the sentinel, and the args after the sentinel, complain.
338 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000339 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCallb46f2872011-09-09 07:56:05 +0000340 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000341 return;
342 }
John McCallb46f2872011-09-09 07:56:05 +0000343
344 // Otherwise, find the sentinel expression.
345 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000346 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000347 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +0000348 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000349
John McCallb46f2872011-09-09 07:56:05 +0000350 // Pick a reasonable string to insert. Optimistically use 'nil' or
351 // 'NULL' if those are actually defined in the context. Only use
352 // 'nil' for ObjC methods, where it's much more likely that the
353 // variadic arguments form a list of object pointers.
354 SourceLocation MissingNilLoc
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000355 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
356 std::string NullValue;
John McCallb46f2872011-09-09 07:56:05 +0000357 if (calleeType == CT_Method &&
358 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000359 NullValue = "nil";
360 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
361 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000362 else
John McCallb46f2872011-09-09 07:56:05 +0000363 NullValue = "(void*) 0";
Eli Friedman9ab36372011-09-27 23:46:37 +0000364
365 if (MissingNilLoc.isInvalid())
366 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
367 else
368 Diag(MissingNilLoc, diag::warn_missing_sentinel)
369 << calleeType
370 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCallb46f2872011-09-09 07:56:05 +0000371 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000372}
373
Richard Trieuba63ce62011-09-09 01:45:06 +0000374SourceRange Sema::getExprRange(Expr *E) const {
375 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000376}
377
Chris Lattner513165e2008-07-25 21:10:04 +0000378//===----------------------------------------------------------------------===//
379// Standard Promotions and Conversions
380//===----------------------------------------------------------------------===//
381
Chris Lattner513165e2008-07-25 21:10:04 +0000382/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000383ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000384 // Handle any placeholder expressions which made it here.
385 if (E->getType()->isPlaceholderType()) {
386 ExprResult result = CheckPlaceholderExpr(E);
387 if (result.isInvalid()) return ExprError();
388 E = result.take();
389 }
390
Chris Lattner513165e2008-07-25 21:10:04 +0000391 QualType Ty = E->getType();
392 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
393
Chris Lattner513165e2008-07-25 21:10:04 +0000394 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000395 E = ImpCastExprToType(E, Context.getPointerType(Ty),
396 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000397 else if (Ty->isArrayType()) {
398 // In C90 mode, arrays only promote to pointers if the array expression is
399 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
400 // type 'array of type' is converted to an expression that has type 'pointer
401 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
402 // that has type 'array of type' ...". The relevant change is "an lvalue"
403 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000404 //
405 // C++ 4.2p1:
406 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
407 // T" can be converted to an rvalue of type "pointer to T".
408 //
David Blaikiebbafb8a2012-03-11 07:00:24 +0000409 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000410 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
411 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000412 }
John Wiegley01296292011-04-08 18:41:53 +0000413 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000414}
415
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000416static void CheckForNullPointerDereference(Sema &S, Expr *E) {
417 // Check to see if we are dereferencing a null pointer. If so,
418 // and if not volatile-qualified, this is undefined behavior that the
419 // optimizer will delete, so warn about it. People sometimes try to use this
420 // to get a deterministic trap and are surprised by clang's behavior. This
421 // only handles the pattern "*null", which is a very syntactic check.
422 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
423 if (UO->getOpcode() == UO_Deref &&
424 UO->getSubExpr()->IgnoreParenCasts()->
425 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
426 !UO->getType().isVolatileQualified()) {
427 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
428 S.PDiag(diag::warn_indirection_through_null)
429 << UO->getSubExpr()->getSourceRange());
430 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
431 S.PDiag(diag::note_indirection_through_null));
432 }
433}
434
John Wiegley01296292011-04-08 18:41:53 +0000435ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000436 // Handle any placeholder expressions which made it here.
437 if (E->getType()->isPlaceholderType()) {
438 ExprResult result = CheckPlaceholderExpr(E);
439 if (result.isInvalid()) return ExprError();
440 E = result.take();
441 }
442
John McCallf3735e02010-12-01 04:43:34 +0000443 // C++ [conv.lval]p1:
444 // A glvalue of a non-function, non-array type T can be
445 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000446 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000447
John McCall27584242010-12-06 20:48:59 +0000448 QualType T = E->getType();
449 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000450
John McCall27584242010-12-06 20:48:59 +0000451 // We don't want to throw lvalue-to-rvalue casts on top of
452 // expressions of certain types in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000453 if (getLangOpts().CPlusPlus &&
John McCall27584242010-12-06 20:48:59 +0000454 (E->getType() == Context.OverloadTy ||
455 T->isDependentType() ||
456 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000457 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000458
459 // The C standard is actually really unclear on this point, and
460 // DR106 tells us what the result should be but not why. It's
461 // generally best to say that void types just doesn't undergo
462 // lvalue-to-rvalue at all. Note that expressions of unqualified
463 // 'void' type are never l-values, but qualified void can be.
464 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000465 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000466
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000467 CheckForNullPointerDereference(*this, E);
468
John McCall27584242010-12-06 20:48:59 +0000469 // C++ [conv.lval]p1:
470 // [...] If T is a non-class type, the type of the prvalue is the
471 // cv-unqualified version of T. Otherwise, the type of the
472 // rvalue is T.
473 //
474 // C99 6.3.2.1p2:
475 // If the lvalue has qualified type, the value has the unqualified
476 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000477 // type of the lvalue.
John McCall27584242010-12-06 20:48:59 +0000478 if (T.hasQualifiers())
479 T = T.getUnqualifiedType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000480
Eli Friedman3bda6b12012-02-02 23:15:15 +0000481 UpdateMarkingForLValueToRValue(E);
482
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000483 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
484 E, 0, VK_RValue));
485
Douglas Gregorc79862f2012-04-12 17:51:55 +0000486 // C11 6.3.2.1p2:
487 // ... if the lvalue has atomic type, the value has the non-atomic version
488 // of the type of the lvalue ...
489 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
490 T = Atomic->getValueType().getUnqualifiedType();
491 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
492 Res.get(), 0, VK_RValue));
493 }
494
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000495 return Res;
John McCall27584242010-12-06 20:48:59 +0000496}
497
John Wiegley01296292011-04-08 18:41:53 +0000498ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
499 ExprResult Res = DefaultFunctionArrayConversion(E);
500 if (Res.isInvalid())
501 return ExprError();
502 Res = DefaultLvalueConversion(Res.take());
503 if (Res.isInvalid())
504 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000505 return Res;
Douglas Gregorb92a1562010-02-03 00:27:59 +0000506}
507
508
Chris Lattner513165e2008-07-25 21:10:04 +0000509/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000510/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000511/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000512/// apply if the array is an argument to the sizeof or address (&) operators.
513/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000514ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000515 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000516 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
517 if (Res.isInvalid())
518 return Owned(E);
519 E = Res.take();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000520
John McCallf3735e02010-12-01 04:43:34 +0000521 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000522 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000523
524 // Half FP is a bit different: it's a storage-only type, meaning that any
525 // "use" of it should be promoted to float.
526 if (Ty->isHalfType())
527 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
528
John McCallf3735e02010-12-01 04:43:34 +0000529 // Try to perform integral promotions if the object has a theoretically
530 // promotable type.
531 if (Ty->isIntegralOrUnscopedEnumerationType()) {
532 // C99 6.3.1.1p2:
533 //
534 // The following may be used in an expression wherever an int or
535 // unsigned int may be used:
536 // - an object or expression with an integer type whose integer
537 // conversion rank is less than or equal to the rank of int
538 // and unsigned int.
539 // - A bit-field of type _Bool, int, signed int, or unsigned int.
540 //
541 // If an int can represent all values of the original type, the
542 // value is converted to an int; otherwise, it is converted to an
543 // unsigned int. These are called the integer promotions. All
544 // other types are unchanged by the integer promotions.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000545
John McCallf3735e02010-12-01 04:43:34 +0000546 QualType PTy = Context.isPromotableBitField(E);
547 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000548 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
549 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000550 }
551 if (Ty->isPromotableIntegerType()) {
552 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000553 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
554 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000555 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000556 }
John Wiegley01296292011-04-08 18:41:53 +0000557 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000558}
559
Chris Lattner2ce500f2008-07-25 22:25:12 +0000560/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000561/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000562/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000563ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
564 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000565 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000566
John Wiegley01296292011-04-08 18:41:53 +0000567 ExprResult Res = UsualUnaryConversions(E);
568 if (Res.isInvalid())
569 return Owned(E);
570 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000571
Chris Lattner2ce500f2008-07-25 22:25:12 +0000572 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000573 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000574 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
575
John McCall4bb057d2011-08-27 22:06:17 +0000576 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000577 // promotion, even on class types, but note:
578 // C++11 [conv.lval]p2:
579 // When an lvalue-to-rvalue conversion occurs in an unevaluated
580 // operand or a subexpression thereof the value contained in the
581 // referenced object is not accessed. Otherwise, if the glvalue
582 // has a class type, the conversion copy-initializes a temporary
583 // of type T from the glvalue and the result of the conversion
584 // is a prvalue for the temporary.
Eli Friedman05e28012012-01-17 02:13:45 +0000585 // FIXME: add some way to gate this entire thing for correctness in
586 // potentially potentially evaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +0000587 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
Eli Friedman05e28012012-01-17 02:13:45 +0000588 ExprResult Temp = PerformCopyInitialization(
589 InitializedEntity::InitializeTemporary(E->getType()),
590 E->getExprLoc(),
591 Owned(E));
592 if (Temp.isInvalid())
593 return ExprError();
594 E = Temp.get();
John McCall29ad95b2011-08-27 01:09:30 +0000595 }
596
John Wiegley01296292011-04-08 18:41:53 +0000597 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000598}
599
Richard Smith55ce3522012-06-25 20:30:08 +0000600/// Determine the degree of POD-ness for an expression.
601/// Incomplete types are considered POD, since this check can be performed
602/// when we're in an unevaluated context.
603Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
Jordan Rose3e0ec582012-07-19 18:10:23 +0000604 if (Ty->isIncompleteType()) {
605 if (Ty->isObjCObjectType())
606 return VAK_Invalid;
Richard Smith55ce3522012-06-25 20:30:08 +0000607 return VAK_Valid;
Jordan Rose3e0ec582012-07-19 18:10:23 +0000608 }
609
610 if (Ty.isCXX98PODType(Context))
611 return VAK_Valid;
612
Richard Smith55ce3522012-06-25 20:30:08 +0000613 // C++0x [expr.call]p7:
614 // Passing a potentially-evaluated argument of class type (Clause 9)
615 // having a non-trivial copy constructor, a non-trivial move constructor,
616 // or a non-trivial destructor, with no corresponding parameter,
617 // is conditionally-supported with implementation-defined semantics.
Richard Smith55ce3522012-06-25 20:30:08 +0000618 if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
619 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
620 if (Record->hasTrivialCopyConstructor() &&
621 Record->hasTrivialMoveConstructor() &&
622 Record->hasTrivialDestructor())
623 return VAK_ValidInCXX11;
624
625 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
626 return VAK_Valid;
627 return VAK_Invalid;
628}
629
630bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
631 // Don't allow one to pass an Objective-C interface to a vararg.
632 const QualType & Ty = E->getType();
633
634 // Complain about passing non-POD types through varargs.
635 switch (isValidVarArgType(Ty)) {
636 case VAK_Valid:
637 break;
638 case VAK_ValidInCXX11:
639 DiagRuntimeBehavior(E->getLocStart(), 0,
640 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
641 << E->getType() << CT);
642 break;
Jordan Rose3e0ec582012-07-19 18:10:23 +0000643 case VAK_Invalid: {
644 if (Ty->isObjCObjectType())
645 return DiagRuntimeBehavior(E->getLocStart(), 0,
646 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
647 << Ty << CT);
648
Richard Smith55ce3522012-06-25 20:30:08 +0000649 return DiagRuntimeBehavior(E->getLocStart(), 0,
650 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
651 << getLangOpts().CPlusPlus0x << Ty << CT);
652 }
Jordan Rose3e0ec582012-07-19 18:10:23 +0000653 }
Richard Smith55ce3522012-06-25 20:30:08 +0000654 // c++ rules are enforced elsewhere.
655 return false;
656}
657
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000658/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
Jordan Rose3e0ec582012-07-19 18:10:23 +0000659/// will create a trap if the resulting type is not a POD type.
John Wiegley01296292011-04-08 18:41:53 +0000660ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000661 FunctionDecl *FDecl) {
Richard Smith7659b122012-06-27 20:29:39 +0000662 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall4124c492011-10-17 18:40:02 +0000663 // Strip the unbridged-cast placeholder expression off, if applicable.
664 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
665 (CT == VariadicMethod ||
666 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
667 E = stripARCUnbridgedCast(E);
668
669 // Otherwise, do normal placeholder checking.
670 } else {
671 ExprResult ExprRes = CheckPlaceholderExpr(E);
672 if (ExprRes.isInvalid())
673 return ExprError();
674 E = ExprRes.take();
675 }
676 }
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000677
John McCall4124c492011-10-17 18:40:02 +0000678 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000679 if (ExprRes.isInvalid())
680 return ExprError();
681 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000682
Richard Smith55ce3522012-06-25 20:30:08 +0000683 // Diagnostics regarding non-POD argument types are
684 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smith56471fd2012-06-27 20:23:58 +0000685 if (isValidVarArgType(E->getType()) == VAK_Invalid) {
Richard Smith55ce3522012-06-25 20:30:08 +0000686 // Turn this into a trap.
687 CXXScopeSpec SS;
688 SourceLocation TemplateKWLoc;
689 UnqualifiedId Name;
690 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
691 E->getLocStart());
692 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
693 Name, true, false);
694 if (TrapFn.isInvalid())
695 return ExprError();
John McCall31168b02011-06-15 23:02:42 +0000696
Richard Smith55ce3522012-06-25 20:30:08 +0000697 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
698 E->getLocStart(), MultiExprArg(),
699 E->getLocEnd());
700 if (Call.isInvalid())
701 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000702
Richard Smith55ce3522012-06-25 20:30:08 +0000703 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
704 Call.get(), E);
705 if (Comma.isInvalid())
706 return ExprError();
707 return Comma.get();
Douglas Gregor253cadf2011-05-21 16:27:21 +0000708 }
Richard Smith55ce3522012-06-25 20:30:08 +0000709
David Blaikiebbafb8a2012-03-11 07:00:24 +0000710 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000711 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000712 diag::err_call_incomplete_argument))
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000713 return ExprError();
Richard Smith55ce3522012-06-25 20:30:08 +0000714
John Wiegley01296292011-04-08 18:41:53 +0000715 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000716}
717
Richard Trieu7aa58f12011-09-02 20:58:51 +0000718/// \brief Converts an integer to complex float type. Helper function of
719/// UsualArithmeticConversions()
720///
721/// \return false if the integer expression is an integer type and is
722/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000723static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
724 ExprResult &ComplexExpr,
725 QualType IntTy,
726 QualType ComplexTy,
727 bool SkipCast) {
728 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
729 if (SkipCast) return false;
730 if (IntTy->isIntegerType()) {
731 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
732 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
733 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000734 CK_FloatingRealToComplex);
735 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +0000736 assert(IntTy->isComplexIntegerType());
737 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000738 CK_IntegralComplexToFloatingComplex);
739 }
740 return false;
741}
742
743/// \brief Takes two complex float types and converts them to the same type.
744/// Helper function of UsualArithmeticConversions()
745static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000746handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
747 ExprResult &RHS, QualType LHSType,
748 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000749 bool IsCompAssign) {
Richard Trieu5065cdd2011-09-06 18:25:09 +0000750 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000751
752 if (order < 0) {
753 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000754 if (!IsCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000755 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
756 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000757 }
758 if (order > 0)
759 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000760 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
761 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000762}
763
764/// \brief Converts otherExpr to complex float and promotes complexExpr if
765/// necessary. Helper function of UsualArithmeticConversions()
766static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuba63ce62011-09-09 01:45:06 +0000767 ExprResult &ComplexExpr,
768 ExprResult &OtherExpr,
769 QualType ComplexTy,
770 QualType OtherTy,
771 bool ConvertComplexExpr,
772 bool ConvertOtherExpr) {
773 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000774
775 // If just the complexExpr is complex, the otherExpr needs to be converted,
776 // and the complexExpr might need to be promoted.
777 if (order > 0) { // complexExpr is wider
778 // float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000779 if (ConvertOtherExpr) {
780 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
781 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
782 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000783 CK_FloatingRealToComplex);
784 }
Richard Trieuba63ce62011-09-09 01:45:06 +0000785 return ComplexTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000786 }
787
788 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000789 QualType result = (order == 0 ? ComplexTy :
790 S.Context.getComplexType(OtherTy));
Richard Trieu7aa58f12011-09-02 20:58:51 +0000791
792 // double -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000793 if (ConvertOtherExpr)
794 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000795 CK_FloatingRealToComplex);
796
797 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000798 if (ConvertComplexExpr && order < 0)
799 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000800 CK_FloatingComplexCast);
801
802 return result;
803}
804
805/// \brief Handle arithmetic conversion with complex types. Helper function of
806/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000807static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
808 ExprResult &RHS, QualType LHSType,
809 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000810 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000811 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000812 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000813 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000814 return LHSType;
815 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000816 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000817 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000818
819 // This handles complex/complex, complex/float, or float/complex.
820 // When both operands are complex, the shorter operand is converted to the
821 // type of the longer, and that is the type of the result. This corresponds
822 // to what is done when combining two real floating-point operands.
823 // The fun begins when size promotion occur across type domains.
824 // From H&S 6.3.4: When one operand is complex and the other is a real
825 // floating-point type, the less precise type is converted, within it's
826 // real or complex domain, to the precision of the other type. For example,
827 // when combining a "long double" with a "double _Complex", the
828 // "double _Complex" is promoted to "long double _Complex".
829
Richard Trieu5065cdd2011-09-06 18:25:09 +0000830 bool LHSComplexFloat = LHSType->isComplexType();
831 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000832
833 // If both are complex, just cast to the more precise type.
834 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000835 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
836 LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000837 IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000838
839 // If only one operand is complex, promote it if necessary and convert the
840 // other operand to complex.
841 if (LHSComplexFloat)
842 return handleOtherComplexFloatConversion(
Richard Trieuba63ce62011-09-09 01:45:06 +0000843 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000844 /*convertOtherExpr*/ true);
845
846 assert(RHSComplexFloat);
847 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000848 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000849 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000850}
851
852/// \brief Hande arithmetic conversion from integer to float. Helper function
853/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +0000854static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
855 ExprResult &IntExpr,
856 QualType FloatTy, QualType IntTy,
857 bool ConvertFloat, bool ConvertInt) {
858 if (IntTy->isIntegerType()) {
859 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +0000860 // Convert intExpr to the lhs floating point type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000861 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000862 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +0000863 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000864 }
865
866 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +0000867 assert(IntTy->isComplexIntegerType());
868 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000869
870 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000871 if (ConvertInt)
872 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000873 CK_IntegralComplexToFloatingComplex);
874
875 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000876 if (ConvertFloat)
877 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000878 CK_FloatingRealToComplex);
879
880 return result;
881}
882
883/// \brief Handle arithmethic conversion with floating point types. Helper
884/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000885static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
886 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000887 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000888 bool LHSFloat = LHSType->isRealFloatingType();
889 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000890
891 // If we have two real floating types, convert the smaller operand
892 // to the bigger result.
893 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000894 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000895 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000896 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
897 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000898 }
899
900 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +0000901 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000902 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
903 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000904 }
905
906 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000907 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000908 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000909 /*convertInt=*/ true);
910 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000911 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000912 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000913 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000914}
915
916/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000917/// of UsualArithmeticConversions()
Richard Trieu7aa58f12011-09-02 20:58:51 +0000918// FIXME: if the operands are (int, _Complex long), we currently
919// don't promote the complex. Also, signedness?
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000920static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
921 ExprResult &RHS, QualType LHSType,
922 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000923 bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000924 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
925 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000926
Richard Trieucfe3f212011-09-06 18:38:41 +0000927 if (LHSComplexInt && RHSComplexInt) {
928 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
929 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000930 assert(order && "inequal types with equal element ordering");
931 if (order > 0) {
932 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000933 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
934 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000935 }
936
Richard Trieuba63ce62011-09-09 01:45:06 +0000937 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000938 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
939 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000940 }
941
Richard Trieucfe3f212011-09-06 18:38:41 +0000942 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000943 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000944 // FIXME: This needs to take integer ranks into account
945 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
946 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000947 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
948 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000949 }
950
Richard Trieucfe3f212011-09-06 18:38:41 +0000951 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000952 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000953 // FIXME: This needs to take integer ranks into account
954 if (!IsCompAssign) {
955 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
956 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000957 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedman47133be2011-11-12 03:56:23 +0000958 }
Richard Trieucfe3f212011-09-06 18:38:41 +0000959 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000960}
961
962/// \brief Handle integer arithmetic conversions. Helper function of
963/// UsualArithmeticConversions()
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000964static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
965 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000966 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000967 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000968 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
969 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
970 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
971 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000972 // Same signedness; use the higher-ranked type
973 if (order >= 0) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000974 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
975 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000976 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000977 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
978 return RHSType;
979 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000980 // The unsigned type has greater than or equal rank to the
981 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000982 if (RHSSigned) {
983 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
984 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000985 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000986 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
987 return RHSType;
988 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000989 // The two types are different widths; if we are here, that
990 // means the signed type is larger than the unsigned type, so
991 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000992 if (LHSSigned) {
993 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
994 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000995 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000996 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
997 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000998 } else {
999 // The signed type is higher-ranked than the unsigned type,
1000 // but isn't actually any bigger (like unsigned int and long
1001 // on most 32-bit systems). Use the unsigned type corresponding
1002 // to the signed type.
1003 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001004 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1005 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuba63ce62011-09-09 01:45:06 +00001006 if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001007 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001008 return result;
1009 }
1010}
1011
Chris Lattner513165e2008-07-25 21:10:04 +00001012/// UsualArithmeticConversions - Performs various conversions that are common to
1013/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +00001014/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +00001015/// responsible for emitting appropriate error diagnostics.
1016/// FIXME: verify the conversion rules for "complex int" are consistent with
1017/// GCC.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001018QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00001019 bool IsCompAssign) {
1020 if (!IsCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001021 LHS = UsualUnaryConversions(LHS.take());
1022 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001023 return QualType();
1024 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00001025
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001026 RHS = UsualUnaryConversions(RHS.take());
1027 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001028 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001029
Mike Stump11289f42009-09-09 15:08:12 +00001030 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +00001031 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001032 QualType LHSType =
1033 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1034 QualType RHSType =
1035 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001036
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001037 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1038 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1039 LHSType = AtomicLHS->getValueType();
1040
Douglas Gregora11693b2008-11-12 17:17:38 +00001041 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001042 if (LHSType == RHSType)
1043 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +00001044
1045 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1046 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001047 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001048 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001049
John McCalld005ac92010-11-13 08:17:45 +00001050 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001051 QualType LHSUnpromotedType = LHSType;
1052 if (LHSType->isPromotableIntegerType())
1053 LHSType = Context.getPromotedIntegerType(LHSType);
1054 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +00001055 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001056 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00001057 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001058 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +00001059
John McCalld005ac92010-11-13 08:17:45 +00001060 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001061 if (LHSType == RHSType)
1062 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +00001063
1064 // At this point, we have two different arithmetic types.
1065
1066 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001067 if (LHSType->isComplexType() || RHSType->isComplexType())
1068 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001069 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001070
1071 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001072 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1073 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001074 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001075
1076 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001077 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +00001078 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001079 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001080
1081 // Finally, we have two differing integer types.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001082 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001083 IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +00001084}
1085
Chris Lattner513165e2008-07-25 21:10:04 +00001086//===----------------------------------------------------------------------===//
1087// Semantic Analysis for various Expression Types
1088//===----------------------------------------------------------------------===//
1089
1090
Peter Collingbourne91147592011-04-15 00:35:48 +00001091ExprResult
1092Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1093 SourceLocation DefaultLoc,
1094 SourceLocation RParenLoc,
1095 Expr *ControllingExpr,
Richard Trieuba63ce62011-09-09 01:45:06 +00001096 MultiTypeArg ArgTypes,
1097 MultiExprArg ArgExprs) {
1098 unsigned NumAssocs = ArgTypes.size();
1099 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +00001100
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001101 ParsedType *ParsedTypes = ArgTypes.data();
1102 Expr **Exprs = ArgExprs.data();
Peter Collingbourne91147592011-04-15 00:35:48 +00001103
1104 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1105 for (unsigned i = 0; i < NumAssocs; ++i) {
1106 if (ParsedTypes[i])
1107 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1108 else
1109 Types[i] = 0;
1110 }
1111
1112 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1113 ControllingExpr, Types, Exprs,
1114 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +00001115 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +00001116 return ER;
1117}
1118
1119ExprResult
1120Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1121 SourceLocation DefaultLoc,
1122 SourceLocation RParenLoc,
1123 Expr *ControllingExpr,
1124 TypeSourceInfo **Types,
1125 Expr **Exprs,
1126 unsigned NumAssocs) {
1127 bool TypeErrorFound = false,
1128 IsResultDependent = ControllingExpr->isTypeDependent(),
1129 ContainsUnexpandedParameterPack
1130 = ControllingExpr->containsUnexpandedParameterPack();
1131
1132 for (unsigned i = 0; i < NumAssocs; ++i) {
1133 if (Exprs[i]->containsUnexpandedParameterPack())
1134 ContainsUnexpandedParameterPack = true;
1135
1136 if (Types[i]) {
1137 if (Types[i]->getType()->containsUnexpandedParameterPack())
1138 ContainsUnexpandedParameterPack = true;
1139
1140 if (Types[i]->getType()->isDependentType()) {
1141 IsResultDependent = true;
1142 } else {
Benjamin Kramere56f3932011-12-23 17:00:35 +00001143 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbourne91147592011-04-15 00:35:48 +00001144 // complete object type other than a variably modified type."
1145 unsigned D = 0;
1146 if (Types[i]->getType()->isIncompleteType())
1147 D = diag::err_assoc_type_incomplete;
1148 else if (!Types[i]->getType()->isObjectType())
1149 D = diag::err_assoc_type_nonobject;
1150 else if (Types[i]->getType()->isVariablyModifiedType())
1151 D = diag::err_assoc_type_variably_modified;
1152
1153 if (D != 0) {
1154 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1155 << Types[i]->getTypeLoc().getSourceRange()
1156 << Types[i]->getType();
1157 TypeErrorFound = true;
1158 }
1159
Benjamin Kramere56f3932011-12-23 17:00:35 +00001160 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbourne91147592011-04-15 00:35:48 +00001161 // selection shall specify compatible types."
1162 for (unsigned j = i+1; j < NumAssocs; ++j)
1163 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1164 Context.typesAreCompatible(Types[i]->getType(),
1165 Types[j]->getType())) {
1166 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1167 diag::err_assoc_compatible_types)
1168 << Types[j]->getTypeLoc().getSourceRange()
1169 << Types[j]->getType()
1170 << Types[i]->getType();
1171 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1172 diag::note_compat_assoc)
1173 << Types[i]->getTypeLoc().getSourceRange()
1174 << Types[i]->getType();
1175 TypeErrorFound = true;
1176 }
1177 }
1178 }
1179 }
1180 if (TypeErrorFound)
1181 return ExprError();
1182
1183 // If we determined that the generic selection is result-dependent, don't
1184 // try to compute the result expression.
1185 if (IsResultDependent)
1186 return Owned(new (Context) GenericSelectionExpr(
1187 Context, KeyLoc, ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001188 llvm::makeArrayRef(Types, NumAssocs),
1189 llvm::makeArrayRef(Exprs, NumAssocs),
1190 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
Peter Collingbourne91147592011-04-15 00:35:48 +00001191
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001192 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001193 unsigned DefaultIndex = -1U;
1194 for (unsigned i = 0; i < NumAssocs; ++i) {
1195 if (!Types[i])
1196 DefaultIndex = i;
1197 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1198 Types[i]->getType()))
1199 CompatIndices.push_back(i);
1200 }
1201
Benjamin Kramere56f3932011-12-23 17:00:35 +00001202 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbourne91147592011-04-15 00:35:48 +00001203 // type compatible with at most one of the types named in its generic
1204 // association list."
1205 if (CompatIndices.size() > 1) {
1206 // We strip parens here because the controlling expression is typically
1207 // parenthesized in macro definitions.
1208 ControllingExpr = ControllingExpr->IgnoreParens();
1209 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1210 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1211 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001212 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001213 E = CompatIndices.end(); I != E; ++I) {
1214 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1215 diag::note_compat_assoc)
1216 << Types[*I]->getTypeLoc().getSourceRange()
1217 << Types[*I]->getType();
1218 }
1219 return ExprError();
1220 }
1221
Benjamin Kramere56f3932011-12-23 17:00:35 +00001222 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbourne91147592011-04-15 00:35:48 +00001223 // its controlling expression shall have type compatible with exactly one of
1224 // the types named in its generic association list."
1225 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1226 // We strip parens here because the controlling expression is typically
1227 // parenthesized in macro definitions.
1228 ControllingExpr = ControllingExpr->IgnoreParens();
1229 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1230 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1231 return ExprError();
1232 }
1233
Benjamin Kramere56f3932011-12-23 17:00:35 +00001234 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbourne91147592011-04-15 00:35:48 +00001235 // type name that is compatible with the type of the controlling expression,
1236 // then the result expression of the generic selection is the expression
1237 // in that generic association. Otherwise, the result expression of the
1238 // generic selection is the expression in the default generic association."
1239 unsigned ResultIndex =
1240 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1241
1242 return Owned(new (Context) GenericSelectionExpr(
1243 Context, KeyLoc, ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001244 llvm::makeArrayRef(Types, NumAssocs),
1245 llvm::makeArrayRef(Exprs, NumAssocs),
1246 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
Peter Collingbourne91147592011-04-15 00:35:48 +00001247 ResultIndex));
1248}
1249
Richard Smith75b67d62012-03-08 01:34:56 +00001250/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1251/// location of the token and the offset of the ud-suffix within it.
1252static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1253 unsigned Offset) {
1254 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001255 S.getLangOpts());
Richard Smith75b67d62012-03-08 01:34:56 +00001256}
1257
Richard Smithbcc22fc2012-03-09 08:00:36 +00001258/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1259/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1260static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1261 IdentifierInfo *UDSuffix,
1262 SourceLocation UDSuffixLoc,
1263 ArrayRef<Expr*> Args,
1264 SourceLocation LitEndLoc) {
1265 assert(Args.size() <= 2 && "too many arguments for literal operator");
1266
1267 QualType ArgTy[2];
1268 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1269 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1270 if (ArgTy[ArgIdx]->isArrayType())
1271 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1272 }
1273
1274 DeclarationName OpName =
1275 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1276 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1277 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1278
1279 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1280 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1281 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1282 return ExprError();
1283
1284 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1285}
1286
Steve Naroff83895f72007-09-16 03:34:24 +00001287/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001288/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1289/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1290/// multiple tokens. However, the common case is that StringToks points to one
1291/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001292///
John McCalldadc5752010-08-24 06:29:42 +00001293ExprResult
Richard Smithbcc22fc2012-03-09 08:00:36 +00001294Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1295 Scope *UDLScope) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001296 assert(NumStringToks && "Must have at least one string!");
1297
Chris Lattner8a24e582009-01-16 18:51:42 +00001298 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001299 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001300 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001301
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001302 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001303 for (unsigned i = 0; i != NumStringToks; ++i)
1304 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001305
Chris Lattner36fc8792008-02-11 00:02:17 +00001306 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001307 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001308 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001309 else if (Literal.isUTF16())
1310 StrTy = Context.Char16Ty;
1311 else if (Literal.isUTF32())
1312 StrTy = Context.Char32Ty;
Eli Friedmanfcec6302011-11-01 02:23:42 +00001313 else if (Literal.isPascal())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001314 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001315
Douglas Gregorfb65e592011-07-27 05:40:30 +00001316 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1317 if (Literal.isWide())
1318 Kind = StringLiteral::Wide;
1319 else if (Literal.isUTF8())
1320 Kind = StringLiteral::UTF8;
1321 else if (Literal.isUTF16())
1322 Kind = StringLiteral::UTF16;
1323 else if (Literal.isUTF32())
1324 Kind = StringLiteral::UTF32;
1325
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001326 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001327 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001328 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001329
Chris Lattner36fc8792008-02-11 00:02:17 +00001330 // Get an array type for the string, according to C99 6.4.5. This includes
1331 // the nul terminator character as well as the string length for pascal
1332 // strings.
1333 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001334 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001335 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001336
Chris Lattner5b183d82006-11-10 05:03:26 +00001337 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smithc67fdd42012-03-07 08:35:16 +00001338 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1339 Kind, Literal.Pascal, StrTy,
1340 &StringTokLocs[0],
1341 StringTokLocs.size());
1342 if (Literal.getUDSuffix().empty())
1343 return Owned(Lit);
1344
1345 // We're building a user-defined literal.
1346 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smith75b67d62012-03-08 01:34:56 +00001347 SourceLocation UDSuffixLoc =
1348 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1349 Literal.getUDSuffixOffset());
Richard Smithc67fdd42012-03-07 08:35:16 +00001350
Richard Smithbcc22fc2012-03-09 08:00:36 +00001351 // Make sure we're allowed user-defined literals here.
1352 if (!UDLScope)
1353 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1354
Richard Smithc67fdd42012-03-07 08:35:16 +00001355 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1356 // operator "" X (str, len)
1357 QualType SizeType = Context.getSizeType();
1358 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1359 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1360 StringTokLocs[0]);
1361 Expr *Args[] = { Lit, LenArg };
Richard Smithbcc22fc2012-03-09 08:00:36 +00001362 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1363 Args, StringTokLocs.back());
Chris Lattner5b183d82006-11-10 05:03:26 +00001364}
1365
John McCalldadc5752010-08-24 06:29:42 +00001366ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001367Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001368 SourceLocation Loc,
1369 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001370 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001371 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001372}
1373
John McCallf4cd4f92011-02-09 01:13:10 +00001374/// BuildDeclRefExpr - Build an expression that references a
1375/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001376ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001377Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001378 const DeclarationNameInfo &NameInfo,
1379 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001380 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001381 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1382 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1383 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1384 CalleeTarget = IdentifyCUDATarget(Callee);
1385 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1386 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1387 << CalleeTarget << D->getIdentifier() << CallerTarget;
1388 Diag(D->getLocation(), diag::note_previous_decl)
1389 << D->getIdentifier();
1390 return ExprError();
1391 }
1392 }
1393
John McCall113bee02012-03-10 09:33:50 +00001394 bool refersToEnclosingScope =
1395 (CurContext != D->getDeclContext() &&
1396 D->getDeclContext()->isFunctionOrMethod());
1397
Eli Friedmanfa0df832012-02-02 03:46:19 +00001398 DeclRefExpr *E = DeclRefExpr::Create(Context,
1399 SS ? SS->getWithLocInContext(Context)
1400 : NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00001401 SourceLocation(),
1402 D, refersToEnclosingScope,
1403 NameInfo, Ty, VK);
Mike Stump11289f42009-09-09 15:08:12 +00001404
Eli Friedmanfa0df832012-02-02 03:46:19 +00001405 MarkDeclRefReferenced(E);
John McCall086a4642010-11-24 05:12:34 +00001406
1407 // Just in case we're building an illegal pointer-to-member.
Richard Smithcaf33902011-10-10 18:28:20 +00001408 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1409 if (FD && FD->isBitField())
John McCall086a4642010-11-24 05:12:34 +00001410 E->setObjectKind(OK_BitField);
1411
1412 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001413}
1414
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001415/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001416/// possibly a list of template arguments.
1417///
1418/// If this produces template arguments, it is permitted to call
1419/// DecomposeTemplateName.
1420///
1421/// This actually loses a lot of source location information for
1422/// non-standard name kinds; we should consider preserving that in
1423/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001424void
1425Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1426 TemplateArgumentListInfo &Buffer,
1427 DeclarationNameInfo &NameInfo,
1428 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001429 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1430 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1431 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1432
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001433 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall10eae182009-11-30 22:42:35 +00001434 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001435 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001436
John McCall3e56fd42010-08-23 07:28:44 +00001437 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001438 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001439 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001440 TemplateArgs = &Buffer;
1441 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001442 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001443 TemplateArgs = 0;
1444 }
1445}
1446
John McCalld681c392009-12-16 08:11:27 +00001447/// Diagnose an empty lookup.
1448///
1449/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001450bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001451 CorrectionCandidateCallback &CCC,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001452 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001453 llvm::ArrayRef<Expr *> Args) {
John McCalld681c392009-12-16 08:11:27 +00001454 DeclarationName Name = R.getLookupName();
1455
John McCalld681c392009-12-16 08:11:27 +00001456 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001457 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001458 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1459 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001460 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001461 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001462 diagnostic_suggest = diag::err_undeclared_use_suggest;
1463 }
John McCalld681c392009-12-16 08:11:27 +00001464
Douglas Gregor598b08f2009-12-31 05:20:13 +00001465 // If the original lookup was an unqualified lookup, fake an
1466 // unqualified lookup. This is useful when (for example) the
1467 // original lookup would not have found something because it was a
1468 // dependent name.
David Blaikiec4c0e8a2012-05-28 01:26:45 +00001469 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1470 ? CurContext : 0;
Francois Pichetde232cb2011-11-25 01:10:54 +00001471 while (DC) {
John McCalld681c392009-12-16 08:11:27 +00001472 if (isa<CXXRecordDecl>(DC)) {
1473 LookupQualifiedName(R, DC);
1474
1475 if (!R.empty()) {
1476 // Don't give errors about ambiguities in this lookup.
1477 R.suppressDiagnostics();
1478
Francois Pichet857f9d62011-11-17 03:44:24 +00001479 // During a default argument instantiation the CurContext points
1480 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1481 // function parameter list, hence add an explicit check.
1482 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1483 ActiveTemplateInstantiations.back().Kind ==
1484 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCalld681c392009-12-16 08:11:27 +00001485 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1486 bool isInstance = CurMethod &&
1487 CurMethod->isInstance() &&
Francois Pichet857f9d62011-11-17 03:44:24 +00001488 DC == CurMethod->getParent() && !isDefaultArgument;
1489
John McCalld681c392009-12-16 08:11:27 +00001490
1491 // Give a code modification hint to insert 'this->'.
1492 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1493 // Actually quite difficult!
Nico Weberdf7dffb2012-06-20 20:21:42 +00001494 if (getLangOpts().MicrosoftMode)
1495 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001496 if (isInstance) {
Nico Weber3c10fb12012-06-22 16:39:39 +00001497 Diag(R.getNameLoc(), diagnostic) << Name
1498 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001499 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1500 CallsUndergoingInstantiation.back()->getCallee());
Nico Weber3c10fb12012-06-22 16:39:39 +00001501
1502
1503 CXXMethodDecl *DepMethod;
1504 if (CurMethod->getTemplatedKind() ==
1505 FunctionDecl::TK_FunctionTemplateSpecialization)
1506 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1507 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1508 else
1509 DepMethod = cast<CXXMethodDecl>(
1510 CurMethod->getInstantiatedFromMemberFunction());
1511 assert(DepMethod && "No template pattern found");
1512
1513 QualType DepThisType = DepMethod->getThisType(Context);
1514 CheckCXXThisCapture(R.getNameLoc());
1515 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1516 R.getNameLoc(), DepThisType, false);
1517 TemplateArgumentListInfo TList;
1518 if (ULE->hasExplicitTemplateArgs())
1519 ULE->copyTemplateArgumentsInto(TList);
1520
1521 CXXScopeSpec SS;
1522 SS.Adopt(ULE->getQualifierLoc());
1523 CXXDependentScopeMemberExpr *DepExpr =
1524 CXXDependentScopeMemberExpr::Create(
1525 Context, DepThis, DepThisType, true, SourceLocation(),
1526 SS.getWithLocInContext(Context),
1527 ULE->getTemplateKeywordLoc(), 0,
1528 R.getLookupNameInfo(),
1529 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1530 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001531 } else {
John McCalld681c392009-12-16 08:11:27 +00001532 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001533 }
John McCalld681c392009-12-16 08:11:27 +00001534
1535 // Do we really want to note all of these?
1536 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1537 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1538
Francois Pichet857f9d62011-11-17 03:44:24 +00001539 // Return true if we are inside a default argument instantiation
1540 // and the found name refers to an instance member function, otherwise
1541 // the function calling DiagnoseEmptyLookup will try to create an
1542 // implicit member call and this is wrong for default argument.
1543 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1544 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1545 return true;
1546 }
1547
John McCalld681c392009-12-16 08:11:27 +00001548 // Tell the callee to try to recover.
1549 return false;
1550 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001551
1552 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001553 }
Francois Pichetde232cb2011-11-25 01:10:54 +00001554
1555 // In Microsoft mode, if we are performing lookup from within a friend
1556 // function definition declared at class scope then we must set
1557 // DC to the lexical parent to be able to search into the parent
1558 // class.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001559 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetde232cb2011-11-25 01:10:54 +00001560 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1561 DC->getLexicalParent()->isRecord())
1562 DC = DC->getLexicalParent();
1563 else
1564 DC = DC->getParent();
John McCalld681c392009-12-16 08:11:27 +00001565 }
1566
Douglas Gregor598b08f2009-12-31 05:20:13 +00001567 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001568 TypoCorrection Corrected;
1569 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001570 S, &SS, CCC))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001571 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1572 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001573 R.setLookupName(Corrected.getCorrection());
1574
Hans Wennborg38198de2011-07-12 08:45:31 +00001575 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001576 if (Corrected.isOverloaded()) {
1577 OverloadCandidateSet OCS(R.getNameLoc());
1578 OverloadCandidateSet::iterator Best;
1579 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1580 CDEnd = Corrected.end();
1581 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001582 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001583 dyn_cast<FunctionTemplateDecl>(*CD))
1584 AddTemplateOverloadCandidate(
1585 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001586 Args, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001587 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1588 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1589 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001590 Args, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001591 }
1592 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1593 case OR_Success:
1594 ND = Best->Function;
1595 break;
1596 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001597 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001598 }
1599 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001600 R.addDecl(ND);
1601 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001602 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001603 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1604 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001605 else
1606 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001607 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001608 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001609 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1610 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001611 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001612 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001613
1614 // Tell the callee to try to recover.
1615 return false;
1616 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001617
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001618 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001619 // FIXME: If we ended up with a typo for a type name or
1620 // Objective-C class name, we're in trouble because the parser
1621 // is in the wrong place to recover. Suggest the typo
1622 // correction, but don't make it a fix-it since we're not going
1623 // to recover well anyway.
1624 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001625 Diag(R.getNameLoc(), diagnostic_suggest)
1626 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001627 else
1628 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001629 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001630 << SS.getRange();
1631
1632 // Don't try to recover; it won't work.
1633 return true;
1634 }
1635 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001636 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001637 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001638 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001639 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001640 else
Douglas Gregor25363982010-01-01 00:15:04 +00001641 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001642 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001643 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001644 return true;
1645 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001646 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001647 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001648
1649 // Emit a special diagnostic for failed member lookups.
1650 // FIXME: computing the declaration context might fail here (?)
1651 if (!SS.isEmpty()) {
1652 Diag(R.getNameLoc(), diag::err_no_member)
1653 << Name << computeDeclContext(SS, false)
1654 << SS.getRange();
1655 return true;
1656 }
1657
John McCalld681c392009-12-16 08:11:27 +00001658 // Give up, we can't recover.
1659 Diag(R.getNameLoc(), diagnostic) << Name;
1660 return true;
1661}
1662
John McCalldadc5752010-08-24 06:29:42 +00001663ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001664 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001665 SourceLocation TemplateKWLoc,
John McCall24d18942010-08-24 22:52:39 +00001666 UnqualifiedId &Id,
1667 bool HasTrailingLParen,
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001668 bool IsAddressOfOperand,
1669 CorrectionCandidateCallback *CCC) {
Richard Trieuba63ce62011-09-09 01:45:06 +00001670 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001671 "cannot be direct & operand and have a trailing lparen");
1672
1673 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001674 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001675
John McCall10eae182009-11-30 22:42:35 +00001676 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001677
1678 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001679 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001680 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001681 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001682
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001683 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001684 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001685 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001686
John McCalle66edc12009-11-24 19:00:30 +00001687 // C++ [temp.dep.expr]p3:
1688 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001689 // -- an identifier that was declared with a dependent type,
1690 // (note: handled after lookup)
1691 // -- a template-id that is dependent,
1692 // (note: handled in BuildTemplateIdExpr)
1693 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001694 // -- a nested-name-specifier that contains a class-name that
1695 // names a dependent type.
1696 // Determine whether this is a member of an unknown specialization;
1697 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001698 bool DependentID = false;
1699 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1700 Name.getCXXNameType()->isDependentType()) {
1701 DependentID = true;
1702 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001703 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001704 if (RequireCompleteDeclContext(SS, DC))
1705 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001706 } else {
1707 DependentID = true;
1708 }
1709 }
1710
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001711 if (DependentID)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001712 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1713 IsAddressOfOperand, TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001714
John McCalle66edc12009-11-24 19:00:30 +00001715 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001716 LookupResult R(*this, NameInfo,
1717 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1718 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001719 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001720 // Lookup the template name again to correctly establish the context in
1721 // which it was found. This is really unfortunate as we already did the
1722 // lookup to determine that it was a template name in the first place. If
1723 // this becomes a performance hit, we can work harder to preserve those
1724 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001725 bool MemberOfUnknownSpecialization;
1726 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1727 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001728
1729 if (MemberOfUnknownSpecialization ||
1730 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001731 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1732 IsAddressOfOperand, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001733 } else {
Benjamin Kramer46921442012-01-20 14:57:34 +00001734 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001735 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001736
Douglas Gregora5226932011-02-04 13:35:07 +00001737 // If the result might be in a dependent base class, this is a dependent
1738 // id-expression.
1739 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001740 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1741 IsAddressOfOperand, TemplateArgs);
1742
John McCalle66edc12009-11-24 19:00:30 +00001743 // If this reference is in an Objective-C method, then we need to do
1744 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001745 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001746 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001747 if (E.isInvalid())
1748 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001749
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001750 if (Expr *Ex = E.takeAs<Expr>())
1751 return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001752 }
Chris Lattner59a25942008-03-31 00:36:02 +00001753 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001754
John McCalle66edc12009-11-24 19:00:30 +00001755 if (R.isAmbiguous())
1756 return ExprError();
1757
Douglas Gregor171c45a2009-02-18 21:56:37 +00001758 // Determine whether this name might be a candidate for
1759 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001760 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001761
John McCalle66edc12009-11-24 19:00:30 +00001762 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001763 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001764 // in C90, extension in C99, forbidden in C++).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001765 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCalle66edc12009-11-24 19:00:30 +00001766 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1767 if (D) R.addDecl(D);
1768 }
1769
1770 // If this name wasn't predeclared and if this is not a function
1771 // call, diagnose the problem.
1772 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001773
1774 // In Microsoft mode, if we are inside a template class member function
1775 // and we can't resolve an identifier then assume the identifier is type
1776 // dependent. The goal is to postpone name lookup to instantiation time
1777 // to be able to search into type dependent base classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001778 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetd8e4e412011-09-24 10:38:05 +00001779 isa<CXXMethodDecl>(CurContext))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001780 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1781 IsAddressOfOperand, TemplateArgs);
Francois Pichetd8e4e412011-09-24 10:38:05 +00001782
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001783 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001784 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCalld681c392009-12-16 08:11:27 +00001785 return ExprError();
1786
1787 assert(!R.empty() &&
1788 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001789
1790 // If we found an Objective-C instance variable, let
1791 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001792 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001793 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1794 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001795 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001796 // In a hopelessly buggy code, Objective-C instance variable
1797 // lookup fails and no expression will be built to reference it.
1798 if (!E.isInvalid() && !E.get())
1799 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001800 return E;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001801 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001802 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001803 }
Mike Stump11289f42009-09-09 15:08:12 +00001804
John McCalle66edc12009-11-24 19:00:30 +00001805 // This is guaranteed from this point on.
1806 assert(!R.empty() || ADL);
1807
John McCall2d74de92009-12-01 22:10:20 +00001808 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001809 // C++ [class.mfct.non-static]p3:
1810 // When an id-expression that is not part of a class member access
1811 // syntax and not used to form a pointer to member is used in the
1812 // body of a non-static member function of class X, if name lookup
1813 // resolves the name in the id-expression to a non-static non-type
1814 // member of some class C, the id-expression is transformed into a
1815 // class member access expression using (*this) as the
1816 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001817 //
1818 // But we don't actually need to do this for '&' operands if R
1819 // resolved to a function or overloaded function set, because the
1820 // expression is ill-formed if it actually works out to be a
1821 // non-static member function:
1822 //
1823 // C++ [expr.ref]p4:
1824 // Otherwise, if E1.E2 refers to a non-static member function. . .
1825 // [t]he expression can be used only as the left-hand operand of a
1826 // member function call.
1827 //
1828 // There are other safeguards against such uses, but it's important
1829 // to get this right here so that we don't end up making a
1830 // spuriously dependent expression if we're inside a dependent
1831 // instance method.
John McCall57500772009-12-16 12:17:52 +00001832 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001833 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001834 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001835 MightBeImplicitMember = true;
1836 else if (!SS.isEmpty())
1837 MightBeImplicitMember = false;
1838 else if (R.isOverloadedResult())
1839 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001840 else if (R.isUnresolvableResult())
1841 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001842 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001843 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1844 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001845
1846 if (MightBeImplicitMember)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001847 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1848 R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001849 }
1850
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001851 if (TemplateArgs || TemplateKWLoc.isValid())
1852 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001853
John McCalle66edc12009-11-24 19:00:30 +00001854 return BuildDeclarationNameExpr(SS, R, ADL);
1855}
1856
John McCall10eae182009-11-30 22:42:35 +00001857/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1858/// declaration name, generally during template instantiation.
1859/// There's a large number of things which don't need to be done along
1860/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001861ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001862Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001863 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001864 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001865 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001866 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1867 NameInfo, /*TemplateArgs=*/0);
John McCalle66edc12009-11-24 19:00:30 +00001868
John McCall0b66eb32010-05-01 00:40:08 +00001869 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001870 return ExprError();
1871
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001872 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001873 LookupQualifiedName(R, DC);
1874
1875 if (R.isAmbiguous())
1876 return ExprError();
1877
1878 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001879 Diag(NameInfo.getLoc(), diag::err_no_member)
1880 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001881 return ExprError();
1882 }
1883
1884 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1885}
1886
1887/// LookupInObjCMethod - The parser has read a name in, and Sema has
1888/// detected that we're currently inside an ObjC method. Perform some
1889/// additional lookup.
1890///
1891/// Ideally, most of this would be done by lookup, but there's
1892/// actually quite a lot of extra work involved.
1893///
1894/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001895ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001896Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001897 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001898 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001899 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001900
John McCalle66edc12009-11-24 19:00:30 +00001901 // There are two cases to handle here. 1) scoped lookup could have failed,
1902 // in which case we should look for an ivar. 2) scoped lookup could have
1903 // found a decl, but that decl is outside the current instance method (i.e.
1904 // a global variable). In these two cases, we do a lookup for an ivar with
1905 // this name, if the lookup sucedes, we replace it our current decl.
1906
1907 // If we're in a class method, we don't normally want to look for
1908 // ivars. But if we don't find anything else, and there's an
1909 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001910 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001911
1912 bool LookForIvars;
1913 if (Lookup.empty())
1914 LookForIvars = true;
1915 else if (IsClassMethod)
1916 LookForIvars = false;
1917 else
1918 LookForIvars = (Lookup.isSingleResult() &&
1919 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001920 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001921 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001922 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001923 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis4e8b1362011-10-19 02:25:16 +00001924 ObjCIvarDecl *IV = 0;
1925 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCalle66edc12009-11-24 19:00:30 +00001926 // Diagnose using an ivar in a class method.
1927 if (IsClassMethod)
1928 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1929 << IV->getDeclName());
1930
1931 // If we're referencing an invalid decl, just return this as a silent
1932 // error node. The error diagnostic was already emitted on the decl.
1933 if (IV->isInvalidDecl())
1934 return ExprError();
1935
1936 // Check if referencing a field with __attribute__((deprecated)).
1937 if (DiagnoseUseOfDecl(IV, Loc))
1938 return ExprError();
1939
1940 // Diagnose the use of an ivar outside of the declaring class.
1941 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001942 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001943 !getLangOpts().DebuggerSupport)
John McCalle66edc12009-11-24 19:00:30 +00001944 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1945
1946 // FIXME: This should use a new expr for a direct reference, don't
1947 // turn this into Self->ivar, just return a BareIVarExpr or something.
1948 IdentifierInfo &II = Context.Idents.get("self");
1949 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001950 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001951 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001952 CXXScopeSpec SelfScopeSpec;
Abramo Bagnara7945c982012-01-27 09:46:47 +00001953 SourceLocation TemplateKWLoc;
1954 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001955 SelfName, false, false);
1956 if (SelfExpr.isInvalid())
1957 return ExprError();
1958
John Wiegley01296292011-04-08 18:41:53 +00001959 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1960 if (SelfExpr.isInvalid())
1961 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001962
Eli Friedmanfa0df832012-02-02 03:46:19 +00001963 MarkAnyDeclReferenced(Loc, IV);
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00001964
1965 ObjCMethodFamily MF = CurMethod->getMethodFamily();
1966 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
1967 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
John McCalle66edc12009-11-24 19:00:30 +00001968 return Owned(new (Context)
1969 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001970 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001971 }
Chris Lattner87313662010-04-12 05:10:17 +00001972 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001973 // We should warn if a local variable hides an ivar.
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001974 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1975 ObjCInterfaceDecl *ClassDeclared;
1976 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1977 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor0b144e12011-12-15 00:29:59 +00001978 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001979 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1980 }
John McCalle66edc12009-11-24 19:00:30 +00001981 }
Fariborz Jahanian028b9e12011-12-20 22:21:08 +00001982 } else if (Lookup.isSingleResult() &&
1983 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
1984 // If accessing a stand-alone ivar in a class method, this is an error.
1985 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
1986 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1987 << IV->getDeclName());
John McCalle66edc12009-11-24 19:00:30 +00001988 }
1989
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001990 if (Lookup.empty() && II && AllowBuiltinCreation) {
1991 // FIXME. Consolidate this with similar code in LookupName.
1992 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001993 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001994 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1995 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1996 S, Lookup.isForRedeclaration(),
1997 Lookup.getNameLoc());
1998 if (D) Lookup.addDecl(D);
1999 }
2000 }
2001 }
John McCalle66edc12009-11-24 19:00:30 +00002002 // Sentinel value saying that we didn't do anything special.
2003 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00002004}
John McCalld14a8642009-11-21 08:51:07 +00002005
John McCall16df1e52010-03-30 21:47:33 +00002006/// \brief Cast a base object to a member's actual type.
2007///
2008/// Logically this happens in three phases:
2009///
2010/// * First we cast from the base type to the naming class.
2011/// The naming class is the class into which we were looking
2012/// when we found the member; it's the qualifier type if a
2013/// qualifier was provided, and otherwise it's the base type.
2014///
2015/// * Next we cast from the naming class to the declaring class.
2016/// If the member we found was brought into a class's scope by
2017/// a using declaration, this is that class; otherwise it's
2018/// the class declaring the member.
2019///
2020/// * Finally we cast from the declaring class to the "true"
2021/// declaring class of the member. This conversion does not
2022/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00002023ExprResult
2024Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002025 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002026 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002027 NamedDecl *Member) {
2028 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2029 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00002030 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002031
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002032 QualType DestRecordType;
2033 QualType DestType;
2034 QualType FromRecordType;
2035 QualType FromType = From->getType();
2036 bool PointerConversions = false;
2037 if (isa<FieldDecl>(Member)) {
2038 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002039
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002040 if (FromType->getAs<PointerType>()) {
2041 DestType = Context.getPointerType(DestRecordType);
2042 FromRecordType = FromType->getPointeeType();
2043 PointerConversions = true;
2044 } else {
2045 DestType = DestRecordType;
2046 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002047 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002048 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2049 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00002050 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002051
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002052 DestType = Method->getThisType(Context);
2053 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002054
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002055 if (FromType->getAs<PointerType>()) {
2056 FromRecordType = FromType->getPointeeType();
2057 PointerConversions = true;
2058 } else {
2059 FromRecordType = FromType;
2060 DestType = DestRecordType;
2061 }
2062 } else {
2063 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002064 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002065 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002066
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002067 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002068 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002069
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002070 // If the unqualified types are the same, no conversion is necessary.
2071 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002072 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002073
John McCall16df1e52010-03-30 21:47:33 +00002074 SourceRange FromRange = From->getSourceRange();
2075 SourceLocation FromLoc = FromRange.getBegin();
2076
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002077 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002078
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002079 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002080 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002081 // class name.
2082 //
2083 // If the member was a qualified name and the qualified referred to a
2084 // specific base subobject type, we'll cast to that intermediate type
2085 // first and then to the object in which the member is declared. That allows
2086 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2087 //
2088 // class Base { public: int x; };
2089 // class Derived1 : public Base { };
2090 // class Derived2 : public Base { };
2091 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2092 //
2093 // void VeryDerived::f() {
2094 // x = 17; // error: ambiguous base subobjects
2095 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2096 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002097 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002098 QualType QType = QualType(Qualifier->getAsType(), 0);
2099 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2100 assert(QType->isRecordType() && "lookup done with non-record type");
2101
2102 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2103
2104 // In C++98, the qualifier type doesn't actually have to be a base
2105 // type of the object type, in which case we just ignore it.
2106 // Otherwise build the appropriate casts.
2107 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002108 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002109 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002110 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002111 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002112
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002113 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002114 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002115 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2116 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002117
2118 FromType = QType;
2119 FromRecordType = QRecordType;
2120
2121 // If the qualifier type was the same as the destination type,
2122 // we're done.
2123 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002124 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002125 }
2126 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002127
John McCall16df1e52010-03-30 21:47:33 +00002128 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002129
John McCall16df1e52010-03-30 21:47:33 +00002130 // If we actually found the member through a using declaration, cast
2131 // down to the using declaration's type.
2132 //
2133 // Pointer equality is fine here because only one declaration of a
2134 // class ever has member declarations.
2135 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2136 assert(isa<UsingShadowDecl>(FoundDecl));
2137 QualType URecordType = Context.getTypeDeclType(
2138 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2139
2140 // We only need to do this if the naming-class to declaring-class
2141 // conversion is non-trivial.
2142 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2143 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002144 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002145 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002146 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002147 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002148
John McCall16df1e52010-03-30 21:47:33 +00002149 QualType UType = URecordType;
2150 if (PointerConversions)
2151 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002152 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2153 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002154 FromType = UType;
2155 FromRecordType = URecordType;
2156 }
2157
2158 // We don't do access control for the conversion from the
2159 // declaring class to the true declaring class.
2160 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002161 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002162
John McCallcf142162010-08-07 06:22:56 +00002163 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002164 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2165 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002166 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002167 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002168
John Wiegley01296292011-04-08 18:41:53 +00002169 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2170 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002171}
Douglas Gregor3256d042009-06-30 15:47:41 +00002172
John McCalle66edc12009-11-24 19:00:30 +00002173bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002174 const LookupResult &R,
2175 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002176 // Only when used directly as the postfix-expression of a call.
2177 if (!HasTrailingLParen)
2178 return false;
2179
2180 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002181 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002182 return false;
2183
2184 // Only in C++ or ObjC++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002185 if (!getLangOpts().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002186 return false;
2187
2188 // Turn off ADL when we find certain kinds of declarations during
2189 // normal lookup:
2190 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2191 NamedDecl *D = *I;
2192
2193 // C++0x [basic.lookup.argdep]p3:
2194 // -- a declaration of a class member
2195 // Since using decls preserve this property, we check this on the
2196 // original decl.
John McCall57500772009-12-16 12:17:52 +00002197 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002198 return false;
2199
2200 // C++0x [basic.lookup.argdep]p3:
2201 // -- a block-scope function declaration that is not a
2202 // using-declaration
2203 // NOTE: we also trigger this for function templates (in fact, we
2204 // don't check the decl type at all, since all other decl types
2205 // turn off ADL anyway).
2206 if (isa<UsingShadowDecl>(D))
2207 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2208 else if (D->getDeclContext()->isFunctionOrMethod())
2209 return false;
2210
2211 // C++0x [basic.lookup.argdep]p3:
2212 // -- a declaration that is neither a function or a function
2213 // template
2214 // And also for builtin functions.
2215 if (isa<FunctionDecl>(D)) {
2216 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2217
2218 // But also builtin functions.
2219 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2220 return false;
2221 } else if (!isa<FunctionTemplateDecl>(D))
2222 return false;
2223 }
2224
2225 return true;
2226}
2227
2228
John McCalld14a8642009-11-21 08:51:07 +00002229/// Diagnoses obvious problems with the use of the given declaration
2230/// as an expression. This is only actually called for lookups that
2231/// were not overloaded, and it doesn't promise that the declaration
2232/// will in fact be used.
2233static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002234 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002235 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2236 return true;
2237 }
2238
2239 if (isa<ObjCInterfaceDecl>(D)) {
2240 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2241 return true;
2242 }
2243
2244 if (isa<NamespaceDecl>(D)) {
2245 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2246 return true;
2247 }
2248
2249 return false;
2250}
2251
John McCalldadc5752010-08-24 06:29:42 +00002252ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002253Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002254 LookupResult &R,
2255 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002256 // If this is a single, fully-resolved result and we don't need ADL,
2257 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002258 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002259 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2260 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002261
2262 // We only need to check the declaration if there's exactly one
2263 // result, because in the overloaded case the results can only be
2264 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002265 if (R.isSingleResult() &&
2266 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002267 return ExprError();
2268
John McCall58cc69d2010-01-27 01:50:18 +00002269 // Otherwise, just build an unresolved lookup expression. Suppress
2270 // any lookup-related diagnostics; we'll hash these out later, when
2271 // we've picked a target.
2272 R.suppressDiagnostics();
2273
John McCalld14a8642009-11-21 08:51:07 +00002274 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002275 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002276 SS.getWithLocInContext(Context),
2277 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002278 NeedsADL, R.isOverloadedResult(),
2279 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002280
2281 return Owned(ULE);
2282}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002283
John McCalld14a8642009-11-21 08:51:07 +00002284/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002285ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002286Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002287 const DeclarationNameInfo &NameInfo,
2288 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002289 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002290 assert(!isa<FunctionTemplateDecl>(D) &&
2291 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002292
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002293 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002294 if (CheckDeclInExpr(*this, Loc, D))
2295 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002296
Douglas Gregore7488b92009-12-01 16:58:18 +00002297 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2298 // Specifically diagnose references to class templates that are missing
2299 // a template argument list.
2300 Diag(Loc, diag::err_template_decl_ref)
2301 << Template << SS.getRange();
2302 Diag(Template->getLocation(), diag::note_template_decl_here);
2303 return ExprError();
2304 }
2305
2306 // Make sure that we're referring to a value.
2307 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2308 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002309 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002310 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002311 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002312 return ExprError();
2313 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002314
Douglas Gregor171c45a2009-02-18 21:56:37 +00002315 // Check whether this declaration can be used. Note that we suppress
2316 // this check when we're going to perform argument-dependent lookup
2317 // on this function name, because this might not be the function
2318 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002319 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002320 return ExprError();
2321
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002322 // Only create DeclRefExpr's for valid Decl's.
2323 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002324 return ExprError();
2325
John McCallf3a88602011-02-03 08:15:49 +00002326 // Handle members of anonymous structs and unions. If we got here,
2327 // and the reference is to a class member indirect field, then this
2328 // must be the subject of a pointer-to-member expression.
2329 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2330 if (!indirectField->isCXXClassMember())
2331 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2332 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002333
Eli Friedman9bb33f52012-02-03 02:04:35 +00002334 {
John McCallf4cd4f92011-02-09 01:13:10 +00002335 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002336 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002337
2338 switch (D->getKind()) {
2339 // Ignore all the non-ValueDecl kinds.
2340#define ABSTRACT_DECL(kind)
2341#define VALUE(type, base)
2342#define DECL(type, base) \
2343 case Decl::type:
2344#include "clang/AST/DeclNodes.inc"
2345 llvm_unreachable("invalid value decl kind");
John McCallf4cd4f92011-02-09 01:13:10 +00002346
2347 // These shouldn't make it here.
2348 case Decl::ObjCAtDefsField:
2349 case Decl::ObjCIvar:
2350 llvm_unreachable("forming non-member reference to ivar?");
John McCallf4cd4f92011-02-09 01:13:10 +00002351
2352 // Enum constants are always r-values and never references.
2353 // Unresolved using declarations are dependent.
2354 case Decl::EnumConstant:
2355 case Decl::UnresolvedUsingValue:
2356 valueKind = VK_RValue;
2357 break;
2358
2359 // Fields and indirect fields that got here must be for
2360 // pointer-to-member expressions; we just call them l-values for
2361 // internal consistency, because this subexpression doesn't really
2362 // exist in the high-level semantics.
2363 case Decl::Field:
2364 case Decl::IndirectField:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002365 assert(getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002366 "building reference to field in C?");
2367
2368 // These can't have reference type in well-formed programs, but
2369 // for internal consistency we do this anyway.
2370 type = type.getNonReferenceType();
2371 valueKind = VK_LValue;
2372 break;
2373
2374 // Non-type template parameters are either l-values or r-values
2375 // depending on the type.
2376 case Decl::NonTypeTemplateParm: {
2377 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2378 type = reftype->getPointeeType();
2379 valueKind = VK_LValue; // even if the parameter is an r-value reference
2380 break;
2381 }
2382
2383 // For non-references, we need to strip qualifiers just in case
2384 // the template parameter was declared as 'const int' or whatever.
2385 valueKind = VK_RValue;
2386 type = type.getUnqualifiedType();
2387 break;
2388 }
2389
2390 case Decl::Var:
2391 // In C, "extern void blah;" is valid and is an r-value.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002392 if (!getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002393 !type.hasQualifiers() &&
2394 type->isVoidType()) {
2395 valueKind = VK_RValue;
2396 break;
2397 }
2398 // fallthrough
2399
2400 case Decl::ImplicitParam:
Douglas Gregor812d8f62012-02-18 05:51:20 +00002401 case Decl::ParmVar: {
John McCallf4cd4f92011-02-09 01:13:10 +00002402 // These are always l-values.
2403 valueKind = VK_LValue;
2404 type = type.getNonReferenceType();
Eli Friedman9bb33f52012-02-03 02:04:35 +00002405
Douglas Gregor812d8f62012-02-18 05:51:20 +00002406 // FIXME: Does the addition of const really only apply in
2407 // potentially-evaluated contexts? Since the variable isn't actually
2408 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie131fcb42012-08-06 22:47:24 +00002409 if (!isUnevaluatedContext()) {
Douglas Gregor812d8f62012-02-18 05:51:20 +00002410 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2411 if (!CapturedType.isNull())
2412 type = CapturedType;
2413 }
2414
John McCallf4cd4f92011-02-09 01:13:10 +00002415 break;
Douglas Gregor812d8f62012-02-18 05:51:20 +00002416 }
2417
John McCallf4cd4f92011-02-09 01:13:10 +00002418 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002419 const FunctionType *fty = type->castAs<FunctionType>();
2420
2421 // If we're referring to a function with an __unknown_anytype
2422 // result type, make the entire expression __unknown_anytype.
2423 if (fty->getResultType() == Context.UnknownAnyTy) {
2424 type = Context.UnknownAnyTy;
2425 valueKind = VK_RValue;
2426 break;
2427 }
2428
John McCallf4cd4f92011-02-09 01:13:10 +00002429 // Functions are l-values in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002430 if (getLangOpts().CPlusPlus) {
John McCallf4cd4f92011-02-09 01:13:10 +00002431 valueKind = VK_LValue;
2432 break;
2433 }
2434
2435 // C99 DR 316 says that, if a function type comes from a
2436 // function definition (without a prototype), that type is only
2437 // used for checking compatibility. Therefore, when referencing
2438 // the function, we pretend that we don't have the full function
2439 // type.
John McCall2979fe02011-04-12 00:42:48 +00002440 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2441 isa<FunctionProtoType>(fty))
2442 type = Context.getFunctionNoProtoType(fty->getResultType(),
2443 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002444
2445 // Functions are r-values in C.
2446 valueKind = VK_RValue;
2447 break;
2448 }
2449
2450 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002451 // If we're referring to a method with an __unknown_anytype
2452 // result type, make the entire expression __unknown_anytype.
2453 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002454 if (const FunctionProtoType *proto
2455 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002456 if (proto->getResultType() == Context.UnknownAnyTy) {
2457 type = Context.UnknownAnyTy;
2458 valueKind = VK_RValue;
2459 break;
2460 }
2461
John McCallf4cd4f92011-02-09 01:13:10 +00002462 // C++ methods are l-values if static, r-values if non-static.
2463 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2464 valueKind = VK_LValue;
2465 break;
2466 }
2467 // fallthrough
2468
2469 case Decl::CXXConversion:
2470 case Decl::CXXDestructor:
2471 case Decl::CXXConstructor:
2472 valueKind = VK_RValue;
2473 break;
2474 }
2475
2476 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2477 }
Chris Lattner17ed4872006-11-20 04:58:19 +00002478}
Chris Lattnere168f762006-11-10 05:29:30 +00002479
John McCall2979fe02011-04-12 00:42:48 +00002480ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002481 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002482
Chris Lattnere168f762006-11-10 05:29:30 +00002483 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002484 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002485 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2486 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber3a691a32012-06-23 02:07:59 +00002487 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattner6307f192008-08-10 01:53:14 +00002488 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002489 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002490
Chris Lattnera81a0272008-01-12 08:14:25 +00002491 // Pre-defined identifiers are of type char[x], where x is the length of the
2492 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002493
Anders Carlsson2fb08242009-09-08 18:24:21 +00002494 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002495 if (!currentDecl && getCurBlock())
2496 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002497 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002498 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002499 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002500 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002501
Anders Carlsson0b209a82009-09-11 01:22:35 +00002502 QualType ResTy;
2503 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2504 ResTy = Context.DependentTy;
2505 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002506 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002507
Anders Carlsson0b209a82009-09-11 01:22:35 +00002508 llvm::APInt LengthI(32, Length + 1);
Nico Weber3052abd2012-06-29 16:39:58 +00002509 if (IT == PredefinedExpr::LFunction)
Nico Weber3a691a32012-06-23 02:07:59 +00002510 ResTy = Context.WCharTy.withConst();
2511 else
2512 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002513 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2514 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002515 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002516}
2517
Richard Smithbcc22fc2012-03-09 08:00:36 +00002518ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002519 SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002520 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002521 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002522 if (Invalid)
2523 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002524
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002525 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002526 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002527 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002528 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002529
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002530 QualType Ty;
Seth Cantrell02f86052012-01-18 12:27:06 +00002531 if (Literal.isWide())
2532 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002533 else if (Literal.isUTF16())
Seth Cantrell02f86052012-01-18 12:27:06 +00002534 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002535 else if (Literal.isUTF32())
Seth Cantrell02f86052012-01-18 12:27:06 +00002536 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002537 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell02f86052012-01-18 12:27:06 +00002538 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002539 else
2540 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002541
Douglas Gregorfb65e592011-07-27 05:40:30 +00002542 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2543 if (Literal.isWide())
2544 Kind = CharacterLiteral::Wide;
2545 else if (Literal.isUTF16())
2546 Kind = CharacterLiteral::UTF16;
2547 else if (Literal.isUTF32())
2548 Kind = CharacterLiteral::UTF32;
2549
Richard Smith75b67d62012-03-08 01:34:56 +00002550 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2551 Tok.getLocation());
2552
2553 if (Literal.getUDSuffix().empty())
2554 return Owned(Lit);
2555
2556 // We're building a user-defined literal.
2557 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2558 SourceLocation UDSuffixLoc =
2559 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2560
Richard Smithbcc22fc2012-03-09 08:00:36 +00002561 // Make sure we're allowed user-defined literals here.
2562 if (!UDLScope)
2563 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2564
Richard Smith75b67d62012-03-08 01:34:56 +00002565 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2566 // operator "" X (ch)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002567 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2568 llvm::makeArrayRef(&Lit, 1),
2569 Tok.getLocation());
Steve Naroffae4143e2007-04-26 20:39:23 +00002570}
2571
Ted Kremeneke65b0862012-03-06 20:05:56 +00002572ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2573 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2574 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2575 Context.IntTy, Loc));
2576}
2577
Richard Smith39570d002012-03-08 08:45:32 +00002578static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2579 QualType Ty, SourceLocation Loc) {
2580 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2581
2582 using llvm::APFloat;
2583 APFloat Val(Format);
2584
2585 APFloat::opStatus result = Literal.GetFloatValue(Val);
2586
2587 // Overflow is always an error, but underflow is only an error if
2588 // we underflowed to zero (APFloat reports denormals as underflow).
2589 if ((result & APFloat::opOverflow) ||
2590 ((result & APFloat::opUnderflow) && Val.isZero())) {
2591 unsigned diagnostic;
2592 SmallString<20> buffer;
2593 if (result & APFloat::opOverflow) {
2594 diagnostic = diag::warn_float_overflow;
2595 APFloat::getLargest(Format).toString(buffer);
2596 } else {
2597 diagnostic = diag::warn_float_underflow;
2598 APFloat::getSmallest(Format).toString(buffer);
2599 }
2600
2601 S.Diag(Loc, diagnostic)
2602 << Ty
2603 << StringRef(buffer.data(), buffer.size());
2604 }
2605
2606 bool isExact = (result == APFloat::opOK);
2607 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2608}
2609
Richard Smithbcc22fc2012-03-09 08:00:36 +00002610ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002611 // Fast path for a single digit (which is quite common). A single digit
Richard Smithbcc22fc2012-03-09 08:00:36 +00002612 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Steve Narofff2fb89e2007-03-13 20:29:44 +00002613 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002614 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002615 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Steve Narofff2fb89e2007-03-13 20:29:44 +00002616 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002617
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002618 SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002619 // Add padding so that NumericLiteralParser can overread by one character.
2620 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002621 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002622
Chris Lattner67ca9252007-05-21 01:08:44 +00002623 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002624 bool Invalid = false;
2625 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2626 if (Invalid)
2627 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002628
Mike Stump11289f42009-09-09 15:08:12 +00002629 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002630 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002631 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002632 return ExprError();
2633
Richard Smith39570d002012-03-08 08:45:32 +00002634 if (Literal.hasUDSuffix()) {
2635 // We're building a user-defined literal.
2636 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2637 SourceLocation UDSuffixLoc =
2638 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2639
Richard Smithbcc22fc2012-03-09 08:00:36 +00002640 // Make sure we're allowed user-defined literals here.
2641 if (!UDLScope)
2642 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smith39570d002012-03-08 08:45:32 +00002643
Richard Smithbcc22fc2012-03-09 08:00:36 +00002644 QualType CookedTy;
Richard Smith39570d002012-03-08 08:45:32 +00002645 if (Literal.isFloatingLiteral()) {
2646 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2647 // long double, the literal is treated as a call of the form
2648 // operator "" X (f L)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002649 CookedTy = Context.LongDoubleTy;
Richard Smith39570d002012-03-08 08:45:32 +00002650 } else {
2651 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2652 // unsigned long long, the literal is treated as a call of the form
2653 // operator "" X (n ULL)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002654 CookedTy = Context.UnsignedLongLongTy;
Richard Smith39570d002012-03-08 08:45:32 +00002655 }
2656
Richard Smithbcc22fc2012-03-09 08:00:36 +00002657 DeclarationName OpName =
2658 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2659 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2660 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2661
2662 // Perform literal operator lookup to determine if we're building a raw
2663 // literal or a cooked one.
2664 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2665 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2666 /*AllowRawAndTemplate*/true)) {
2667 case LOLR_Error:
2668 return ExprError();
2669
2670 case LOLR_Cooked: {
2671 Expr *Lit;
2672 if (Literal.isFloatingLiteral()) {
2673 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2674 } else {
2675 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2676 if (Literal.GetIntegerValue(ResultVal))
2677 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2678 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2679 Tok.getLocation());
2680 }
2681 return BuildLiteralOperatorCall(R, OpNameInfo,
2682 llvm::makeArrayRef(&Lit, 1),
2683 Tok.getLocation());
2684 }
2685
2686 case LOLR_Raw: {
2687 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2688 // literal is treated as a call of the form
2689 // operator "" X ("n")
2690 SourceLocation TokLoc = Tok.getLocation();
2691 unsigned Length = Literal.getUDSuffixOffset();
2692 QualType StrTy = Context.getConstantArrayType(
2693 Context.CharTy, llvm::APInt(32, Length + 1),
2694 ArrayType::Normal, 0);
2695 Expr *Lit = StringLiteral::Create(
2696 Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
2697 /*Pascal*/false, StrTy, &TokLoc, 1);
2698 return BuildLiteralOperatorCall(R, OpNameInfo,
2699 llvm::makeArrayRef(&Lit, 1), TokLoc);
2700 }
2701
2702 case LOLR_Template:
2703 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2704 // template), L is treated as a call fo the form
2705 // operator "" X <'c1', 'c2', ... 'ck'>()
2706 // where n is the source character sequence c1 c2 ... ck.
2707 TemplateArgumentListInfo ExplicitArgs;
2708 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2709 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2710 llvm::APSInt Value(CharBits, CharIsUnsigned);
2711 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2712 Value = ThisTokBegin[I];
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002713 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002714 TemplateArgumentLocInfo ArgInfo;
2715 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2716 }
2717 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2718 Tok.getLocation(), &ExplicitArgs);
2719 }
2720
2721 llvm_unreachable("unexpected literal operator lookup result");
Richard Smith39570d002012-03-08 08:45:32 +00002722 }
2723
Chris Lattner1c20a172007-08-26 03:42:43 +00002724 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002725
Chris Lattner1c20a172007-08-26 03:42:43 +00002726 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002727 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002728 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002729 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002730 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002731 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002732 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002733 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002734
Richard Smith39570d002012-03-08 08:45:32 +00002735 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002736
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002737 if (Ty == Context.DoubleTy) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002738 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002739 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002740 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002741 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002742 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002743 }
2744 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002745 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002746 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002747 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002748 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002749
Neil Boothac582c52007-08-29 22:00:19 +00002750 // long long is a C99 feature.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002751 if (!getLangOpts().C99 && Literal.isLongLong)
Richard Smith0bf8a4922011-10-18 20:49:44 +00002752 Diag(Tok.getLocation(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002753 getLangOpts().CPlusPlus0x ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002754 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Neil Boothac582c52007-08-29 22:00:19 +00002755
Chris Lattner67ca9252007-05-21 01:08:44 +00002756 // Get the value in the widest-possible width.
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002757 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2758 // The microsoft literal suffix extensions support 128-bit literals, which
2759 // may be wider than [u]intmax_t.
2760 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2761 MaxWidth = 128;
2762 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002763
Chris Lattner67ca9252007-05-21 01:08:44 +00002764 if (Literal.GetIntegerValue(ResultVal)) {
2765 // If this value didn't fit into uintmax_t, warn and force to ull.
2766 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002767 Ty = Context.UnsignedLongLongTy;
2768 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002769 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002770 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002771 // If this value fits into a ULL, try to figure out what else it fits into
2772 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002773
Chris Lattner67ca9252007-05-21 01:08:44 +00002774 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2775 // be an unsigned int.
2776 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2777
2778 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002779 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002780 if (!Literal.isLong && !Literal.isLongLong) {
2781 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002782 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002783
Chris Lattner67ca9252007-05-21 01:08:44 +00002784 // Does it fit in a unsigned int?
2785 if (ResultVal.isIntN(IntSize)) {
2786 // Does it fit in a signed int?
2787 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002788 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002789 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002790 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002791 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002792 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002793 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002794
Chris Lattner67ca9252007-05-21 01:08:44 +00002795 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002796 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002797 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002798
Chris Lattner67ca9252007-05-21 01:08:44 +00002799 // Does it fit in a unsigned long?
2800 if (ResultVal.isIntN(LongSize)) {
2801 // Does it fit in a signed long?
2802 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002803 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002804 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002805 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002806 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002807 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002808 }
2809
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002810 // Check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002811 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002812 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002813
Chris Lattner67ca9252007-05-21 01:08:44 +00002814 // Does it fit in a unsigned long long?
2815 if (ResultVal.isIntN(LongLongSize)) {
2816 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002817 // To be compatible with MSVC, hex integer literals ending with the
2818 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002819 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002820 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002821 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002822 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002823 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002824 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002825 }
2826 }
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002827
2828 // If it doesn't fit in unsigned long long, and we're using Microsoft
2829 // extensions, then its a 128-bit integer literal.
2830 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2831 if (Literal.isUnsigned)
2832 Ty = Context.UnsignedInt128Ty;
2833 else
2834 Ty = Context.Int128Ty;
2835 Width = 128;
2836 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002837
Chris Lattner67ca9252007-05-21 01:08:44 +00002838 // If we still couldn't decide a type, we probably have something that
2839 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002840 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002841 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002842 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002843 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002844 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002845
Chris Lattner55258cf2008-05-09 05:59:00 +00002846 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002847 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002848 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002849 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002850 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002851
Chris Lattner1c20a172007-08-26 03:42:43 +00002852 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2853 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002854 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002855 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002856
2857 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002858}
2859
Richard Trieuba63ce62011-09-09 01:45:06 +00002860ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002861 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002862 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002863}
2864
Chandler Carruth62da79c2011-05-26 08:53:12 +00002865static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2866 SourceLocation Loc,
2867 SourceRange ArgRange) {
2868 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2869 // scalar or vector data type argument..."
2870 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2871 // type (C99 6.2.5p18) or void.
2872 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2873 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2874 << T << ArgRange;
2875 return true;
2876 }
2877
2878 assert((T->isVoidType() || !T->isIncompleteType()) &&
2879 "Scalar types should always be complete");
2880 return false;
2881}
2882
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002883static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2884 SourceLocation Loc,
2885 SourceRange ArgRange,
2886 UnaryExprOrTypeTrait TraitKind) {
2887 // C99 6.5.3.4p1:
2888 if (T->isFunctionType()) {
2889 // alignof(function) is allowed as an extension.
2890 if (TraitKind == UETT_SizeOf)
2891 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2892 return false;
2893 }
2894
2895 // Allow sizeof(void)/alignof(void) as an extension.
2896 if (T->isVoidType()) {
2897 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2898 return false;
2899 }
2900
2901 return true;
2902}
2903
2904static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2905 SourceLocation Loc,
2906 SourceRange ArgRange,
2907 UnaryExprOrTypeTrait TraitKind) {
John McCallf2538342012-07-31 05:14:30 +00002908 // Reject sizeof(interface) and sizeof(interface<proto>) if the
2909 // runtime doesn't allow it.
2910 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002911 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2912 << T << (TraitKind == UETT_SizeOf)
2913 << ArgRange;
2914 return true;
2915 }
2916
2917 return false;
2918}
2919
Chandler Carruth14502c22011-05-26 08:53:10 +00002920/// \brief Check the constrains on expression operands to unary type expression
2921/// and type traits.
2922///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002923/// Completes any types necessary and validates the constraints on the operand
2924/// expression. The logic mostly mirrors the type-based overload, but may modify
2925/// the expression as it completes the type for that expression through template
2926/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00002927bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00002928 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002929 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002930
2931 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2932 // the result is the size of the referenced type."
2933 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2934 // result shall be the alignment of the referenced type."
2935 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2936 ExprTy = Ref->getPointeeType();
2937
2938 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002939 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2940 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00002941
2942 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002943 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2944 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002945 return false;
2946
Richard Trieuba63ce62011-09-09 01:45:06 +00002947 if (RequireCompleteExprType(E,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002948 diag::err_sizeof_alignof_incomplete_type,
2949 ExprKind, E->getSourceRange()))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002950 return true;
2951
2952 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00002953 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002954 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2955 ExprTy = Ref->getPointeeType();
2956
Richard Trieuba63ce62011-09-09 01:45:06 +00002957 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2958 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002959 return true;
2960
Nico Weber0870deb2011-06-15 02:47:03 +00002961 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002962 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00002963 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2964 QualType OType = PVD->getOriginalType();
2965 QualType Type = PVD->getType();
2966 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002967 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00002968 << Type << OType;
2969 Diag(PVD->getLocation(), diag::note_declared_at);
2970 }
2971 }
2972 }
2973 }
2974
Chandler Carruth7c430c02011-05-27 01:33:31 +00002975 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002976}
2977
2978/// \brief Check the constraints on operands to unary expression and type
2979/// traits.
2980///
2981/// This will complete any types necessary, and validate the various constraints
2982/// on those operands.
2983///
Steve Naroff71b59a92007-06-04 22:22:31 +00002984/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002985/// C99 6.3.2.1p[2-4] all state:
2986/// Except when it is the operand of the sizeof operator ...
2987///
2988/// C++ [expr.sizeof]p4
2989/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2990/// standard conversions are not applied to the operand of sizeof.
2991///
2992/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00002993bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002994 SourceLocation OpLoc,
2995 SourceRange ExprRange,
2996 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002997 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002998 return false;
2999
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003000 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3001 // the result is the size of the referenced type."
3002 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3003 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00003004 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3005 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003006
Chandler Carruth62da79c2011-05-26 08:53:12 +00003007 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00003008 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003009
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003010 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00003011 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003012 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00003013 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003014
Richard Trieuba63ce62011-09-09 01:45:06 +00003015 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003016 diag::err_sizeof_alignof_incomplete_type,
3017 ExprKind, ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00003018 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003019
Richard Trieuba63ce62011-09-09 01:45:06 +00003020 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003021 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00003022 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003023
Chris Lattner62975a72009-04-24 00:30:45 +00003024 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00003025}
3026
Chandler Carruth14502c22011-05-26 08:53:10 +00003027static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00003028 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003029
Mike Stump11289f42009-09-09 15:08:12 +00003030 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00003031 if (isa<DeclRefExpr>(E))
3032 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003033
3034 // Cannot know anything else if the expression is dependent.
3035 if (E->isTypeDependent())
3036 return false;
3037
Douglas Gregor71235ec2009-05-02 02:18:30 +00003038 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003039 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3040 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003041 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00003042 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003043
3044 // Alignment of a field access is always okay, so long as it isn't a
3045 // bit-field.
3046 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00003047 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003048 return false;
3049
Chandler Carruth14502c22011-05-26 08:53:10 +00003050 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003051}
3052
Chandler Carruth14502c22011-05-26 08:53:10 +00003053bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003054 E = E->IgnoreParens();
3055
3056 // Cannot know anything else if the expression is dependent.
3057 if (E->isTypeDependent())
3058 return false;
3059
Chandler Carruth14502c22011-05-26 08:53:10 +00003060 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00003061}
3062
Douglas Gregor0950e412009-03-13 21:01:28 +00003063/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00003064ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003065Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3066 SourceLocation OpLoc,
3067 UnaryExprOrTypeTrait ExprKind,
3068 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00003069 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00003070 return ExprError();
3071
John McCallbcd03502009-12-07 02:54:59 +00003072 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00003073
Douglas Gregor0950e412009-03-13 21:01:28 +00003074 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00003075 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00003076 return ExprError();
3077
3078 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003079 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3080 Context.getSizeType(),
3081 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003082}
3083
3084/// \brief Build a sizeof or alignof expression given an expression
3085/// operand.
John McCalldadc5752010-08-24 06:29:42 +00003086ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00003087Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3088 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00003089 ExprResult PE = CheckPlaceholderExpr(E);
3090 if (PE.isInvalid())
3091 return ExprError();
3092
3093 E = PE.get();
3094
Douglas Gregor0950e412009-03-13 21:01:28 +00003095 // Verify that the operand is valid.
3096 bool isInvalid = false;
3097 if (E->isTypeDependent()) {
3098 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003099 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003100 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003101 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003102 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00003103 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00003104 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00003105 isInvalid = true;
3106 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00003107 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00003108 }
3109
3110 if (isInvalid)
3111 return ExprError();
3112
Eli Friedmane0afc982012-01-21 01:01:51 +00003113 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3114 PE = TranformToPotentiallyEvaluated(E);
3115 if (PE.isInvalid()) return ExprError();
3116 E = PE.take();
3117 }
3118
Douglas Gregor0950e412009-03-13 21:01:28 +00003119 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00003120 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00003121 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00003122 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003123}
3124
Peter Collingbournee190dee2011-03-11 19:24:49 +00003125/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3126/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003127/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003128ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003129Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003130 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003131 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003132 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003133 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003134
Richard Trieuba63ce62011-09-09 01:45:06 +00003135 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00003136 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003137 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003138 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003139 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003140
Douglas Gregor0950e412009-03-13 21:01:28 +00003141 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00003142 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003143 return Result;
Chris Lattnere168f762006-11-10 05:29:30 +00003144}
3145
John Wiegley01296292011-04-08 18:41:53 +00003146static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003147 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00003148 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003149 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003150
John McCall34376a62010-12-04 03:47:34 +00003151 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003152 if (V.get()->getObjectKind() != OK_Ordinary) {
3153 V = S.DefaultLvalueConversion(V.take());
3154 if (V.isInvalid())
3155 return QualType();
3156 }
John McCall34376a62010-12-04 03:47:34 +00003157
Chris Lattnere267f5d2007-08-26 05:39:26 +00003158 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003159 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003160 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003161
Chris Lattnere267f5d2007-08-26 05:39:26 +00003162 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003163 if (V.get()->getType()->isArithmeticType())
3164 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003165
John McCall36226622010-10-12 02:09:17 +00003166 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003167 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003168 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003169 if (PR.get() != V.get()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003170 V = PR;
Richard Trieuba63ce62011-09-09 01:45:06 +00003171 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00003172 }
3173
Chris Lattnere267f5d2007-08-26 05:39:26 +00003174 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003175 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00003176 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003177 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003178}
3179
3180
Chris Lattnere168f762006-11-10 05:29:30 +00003181
John McCalldadc5752010-08-24 06:29:42 +00003182ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003183Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003184 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003185 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003186 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003187 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003188 case tok::plusplus: Opc = UO_PostInc; break;
3189 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003190 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003191
Sebastian Redla9351792012-02-11 23:51:47 +00003192 // Since this might is a postfix expression, get rid of ParenListExprs.
3193 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3194 if (Result.isInvalid()) return ExprError();
3195 Input = Result.take();
3196
John McCallb268a282010-08-23 23:25:46 +00003197 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003198}
3199
John McCallf2538342012-07-31 05:14:30 +00003200/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3201///
3202/// \return true on error
3203static bool checkArithmeticOnObjCPointer(Sema &S,
3204 SourceLocation opLoc,
3205 Expr *op) {
3206 assert(op->getType()->isObjCObjectPointerType());
3207 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3208 return false;
3209
3210 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3211 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3212 << op->getSourceRange();
3213 return true;
3214}
3215
John McCalldadc5752010-08-24 06:29:42 +00003216ExprResult
John McCallb268a282010-08-23 23:25:46 +00003217Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3218 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003219 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003220 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003221 if (Result.isInvalid()) return ExprError();
3222 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003223
John McCallb268a282010-08-23 23:25:46 +00003224 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003225
David Blaikiebbafb8a2012-03-11 07:00:24 +00003226 if (getLangOpts().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003227 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003228 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003229 Context.DependentTy,
3230 VK_LValue, OK_Ordinary,
3231 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003232 }
3233
David Blaikiebbafb8a2012-03-11 07:00:24 +00003234 if (getLangOpts().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003235 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003236 LHSExp->getType()->isEnumeralType() ||
3237 RHSExp->getType()->isRecordType() ||
Ted Kremeneke65b0862012-03-06 20:05:56 +00003238 RHSExp->getType()->isEnumeralType()) &&
3239 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCallb268a282010-08-23 23:25:46 +00003240 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003241 }
3242
John McCallb268a282010-08-23 23:25:46 +00003243 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003244}
3245
John McCalldadc5752010-08-24 06:29:42 +00003246ExprResult
John McCallb268a282010-08-23 23:25:46 +00003247Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003248 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00003249 Expr *LHSExp = Base;
3250 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003251
Chris Lattner36d572b2007-07-16 00:14:47 +00003252 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003253 if (!LHSExp->getType()->getAs<VectorType>()) {
3254 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3255 if (Result.isInvalid())
3256 return ExprError();
3257 LHSExp = Result.take();
3258 }
3259 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3260 if (Result.isInvalid())
3261 return ExprError();
3262 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003263
Chris Lattner36d572b2007-07-16 00:14:47 +00003264 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003265 ExprValueKind VK = VK_LValue;
3266 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003267
Steve Naroffc1aadb12007-03-28 21:49:40 +00003268 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003269 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003270 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003271 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003272 Expr *BaseExpr, *IndexExpr;
3273 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003274 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3275 BaseExpr = LHSExp;
3276 IndexExpr = RHSExp;
3277 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003278 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003279 BaseExpr = LHSExp;
3280 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003281 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003282 } else if (const ObjCObjectPointerType *PTy =
John McCallf2538342012-07-31 05:14:30 +00003283 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003284 BaseExpr = LHSExp;
3285 IndexExpr = RHSExp;
John McCallf2538342012-07-31 05:14:30 +00003286
3287 // Use custom logic if this should be the pseudo-object subscript
3288 // expression.
3289 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3290 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3291
Steve Naroff7cae42b2009-07-10 23:34:53 +00003292 ResultType = PTy->getPointeeType();
John McCallf2538342012-07-31 05:14:30 +00003293 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3294 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3295 << ResultType << BaseExpr->getSourceRange();
3296 return ExprError();
3297 }
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00003298 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3299 // Handle the uncommon case of "123[Ptr]".
3300 BaseExpr = RHSExp;
3301 IndexExpr = LHSExp;
3302 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003303 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003304 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003305 // Handle the uncommon case of "123[Ptr]".
3306 BaseExpr = RHSExp;
3307 IndexExpr = LHSExp;
3308 ResultType = PTy->getPointeeType();
John McCallf2538342012-07-31 05:14:30 +00003309 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3310 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3311 << ResultType << BaseExpr->getSourceRange();
3312 return ExprError();
3313 }
John McCall9dd450b2009-09-21 23:43:11 +00003314 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003315 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003316 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003317 VK = LHSExp->getValueKind();
3318 if (VK != VK_RValue)
3319 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003320
Chris Lattner36d572b2007-07-16 00:14:47 +00003321 // FIXME: need to deal with const...
3322 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003323 } else if (LHSTy->isArrayType()) {
3324 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003325 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003326 // wasn't promoted because of the C90 rule that doesn't
3327 // allow promoting non-lvalue arrays. Warn, then
3328 // force the promotion here.
3329 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3330 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003331 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3332 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003333 LHSTy = LHSExp->getType();
3334
3335 BaseExpr = LHSExp;
3336 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003337 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003338 } else if (RHSTy->isArrayType()) {
3339 // Same as previous, except for 123[f().a] case
3340 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3341 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003342 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3343 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003344 RHSTy = RHSExp->getType();
3345
3346 BaseExpr = RHSExp;
3347 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003348 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003349 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003350 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3351 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003352 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003353 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003354 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003355 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3356 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003357
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003358 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003359 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3360 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003361 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3362
Douglas Gregorac1fb652009-03-24 19:52:54 +00003363 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003364 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3365 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003366 // incomplete types are not object types.
3367 if (ResultType->isFunctionType()) {
3368 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3369 << ResultType << BaseExpr->getSourceRange();
3370 return ExprError();
3371 }
Mike Stump11289f42009-09-09 15:08:12 +00003372
David Blaikiebbafb8a2012-03-11 07:00:24 +00003373 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003374 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003375 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3376 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003377
3378 // C forbids expressions of unqualified void type from being l-values.
3379 // See IsCForbiddenLValueType.
3380 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003381 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003382 RequireCompleteType(LLoc, ResultType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003383 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003384 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003385
John McCall4bc41ae2010-11-18 19:01:18 +00003386 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003387 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003388
Mike Stump4e1f26a2009-02-19 03:04:26 +00003389 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003390 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003391}
3392
John McCalldadc5752010-08-24 06:29:42 +00003393ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003394 FunctionDecl *FD,
3395 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003396 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003397 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003398 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003399 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003400 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003401 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003402 return ExprError();
3403 }
3404
3405 if (Param->hasUninstantiatedDefaultArg()) {
3406 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003407
Richard Smith505df232012-07-22 23:45:10 +00003408 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3409 Param);
3410
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003411 // Instantiate the expression.
3412 MultiLevelTemplateArgumentList ArgList
3413 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003414
Nico Weber44887f62010-11-29 18:19:25 +00003415 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003416 = ArgList.getInnermost();
Richard Smith80934652012-07-16 01:09:10 +00003417 InstantiatingTemplate Inst(*this, CallLoc, Param,
3418 ArrayRef<TemplateArgument>(Innermost.first,
3419 Innermost.second));
Richard Smith8a874c92012-07-08 02:38:24 +00003420 if (Inst)
3421 return ExprError();
Anders Carlsson355933d2009-08-25 03:49:14 +00003422
Nico Weber44887f62010-11-29 18:19:25 +00003423 ExprResult Result;
3424 {
3425 // C++ [dcl.fct.default]p5:
3426 // The names in the [default argument] expression are bound, and
3427 // the semantic constraints are checked, at the point where the
3428 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003429 ContextRAII SavedContext(*this, FD);
Douglas Gregora86bc002012-02-16 21:36:18 +00003430 LocalInstantiationScope Local(*this);
Nico Weber44887f62010-11-29 18:19:25 +00003431 Result = SubstExpr(UninstExpr, ArgList);
3432 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003433 if (Result.isInvalid())
3434 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003435
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003436 // Check the expression as an initializer for the parameter.
3437 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003438 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003439 InitializationKind Kind
3440 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003441 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003442 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003443
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003444 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003445 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003446 if (Result.isInvalid())
3447 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003448
David Blaikief68e8092012-04-30 18:21:31 +00003449 Expr *Arg = Result.takeAs<Expr>();
David Blaikie18e9ac72012-05-15 21:57:38 +00003450 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003451 // Build the default argument expression.
David Blaikief68e8092012-04-30 18:21:31 +00003452 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson355933d2009-08-25 03:49:14 +00003453 }
3454
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003455 // If the default expression creates temporaries, we need to
3456 // push them to the current stack of expression temporaries so they'll
3457 // be properly destroyed.
3458 // FIXME: We should really be rebuilding the default argument with new
3459 // bound temporaries; see the comment in PR5810.
John McCall28fc7092011-11-10 05:35:25 +00003460 // We don't need to do that with block decls, though, because
3461 // blocks in default argument expression can never capture anything.
3462 if (isa<ExprWithCleanups>(Param->getInit())) {
3463 // Set the "needs cleanups" bit regardless of whether there are
3464 // any explicit objects.
John McCall31168b02011-06-15 23:02:42 +00003465 ExprNeedsCleanups = true;
John McCall28fc7092011-11-10 05:35:25 +00003466
3467 // Append all the objects to the cleanup list. Right now, this
3468 // should always be a no-op, because blocks in default argument
3469 // expressions should never be able to capture anything.
3470 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3471 "default argument expression has capturing blocks?");
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003472 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003473
3474 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003475 // Just mark all of the declarations in this potentially-evaluated expression
3476 // as being "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +00003477 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3478 /*SkipLocalVariables=*/true);
Douglas Gregor033f6752009-12-23 23:03:06 +00003479 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003480}
3481
Richard Smith55ce3522012-06-25 20:30:08 +00003482
3483Sema::VariadicCallType
3484Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3485 Expr *Fn) {
3486 if (Proto && Proto->isVariadic()) {
3487 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3488 return VariadicConstructor;
3489 else if (Fn && Fn->getType()->isBlockPointerType())
3490 return VariadicBlock;
3491 else if (FDecl) {
3492 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3493 if (Method->isInstance())
3494 return VariadicMethod;
3495 }
3496 return VariadicFunction;
3497 }
3498 return VariadicDoesNotApply;
3499}
3500
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003501/// ConvertArgumentsForCall - Converts the arguments specified in
3502/// Args/NumArgs to the parameter types of the function FDecl with
3503/// function prototype Proto. Call is the call expression itself, and
3504/// Fn is the function expression. For a C++ member function, this
3505/// routine does not attempt to convert the object argument. Returns
3506/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003507bool
3508Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003509 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003510 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003511 Expr **Args, unsigned NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003512 SourceLocation RParenLoc,
3513 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00003514 // Bail out early if calling a builtin with custom typechecking.
3515 // We don't need to do this in the
3516 if (FDecl)
3517 if (unsigned ID = FDecl->getBuiltinID())
3518 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3519 return false;
3520
Mike Stump4e1f26a2009-02-19 03:04:26 +00003521 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003522 // assignment, to the types of the corresponding parameter, ...
3523 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003524 bool Invalid = false;
Peter Collingbourne740afe22011-10-02 23:49:20 +00003525 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003526 unsigned FnKind = Fn->getType()->isBlockPointerType()
3527 ? 1 /* block */
3528 : (IsExecConfig ? 3 /* kernel function (exec config) */
3529 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003530
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003531 // If too few arguments are available (and we don't have default
3532 // arguments for the remaining parameters), don't make the call.
3533 if (NumArgs < NumArgsInProto) {
Peter Collingbourne740afe22011-10-02 23:49:20 +00003534 if (NumArgs < MinArgs) {
Richard Smith10ff50d2012-05-11 05:16:41 +00003535 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3536 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3537 ? diag::err_typecheck_call_too_few_args_one
3538 : diag::err_typecheck_call_too_few_args_at_least_one)
3539 << FnKind
3540 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3541 else
3542 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3543 ? diag::err_typecheck_call_too_few_args
3544 : diag::err_typecheck_call_too_few_args_at_least)
3545 << FnKind
3546 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003547
3548 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003549 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003550 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3551 << FDecl;
3552
3553 return true;
3554 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003555 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003556 }
3557
3558 // If too many are passed and not variadic, error on the extras and drop
3559 // them.
3560 if (NumArgs > NumArgsInProto) {
3561 if (!Proto->isVariadic()) {
Richard Smithd72da152012-05-15 06:21:54 +00003562 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3563 Diag(Args[NumArgsInProto]->getLocStart(),
3564 MinArgs == NumArgsInProto
3565 ? diag::err_typecheck_call_too_many_args_one
3566 : diag::err_typecheck_call_too_many_args_at_most_one)
3567 << FnKind
3568 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3569 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3570 Args[NumArgs-1]->getLocEnd());
3571 else
3572 Diag(Args[NumArgsInProto]->getLocStart(),
3573 MinArgs == NumArgsInProto
3574 ? diag::err_typecheck_call_too_many_args
3575 : diag::err_typecheck_call_too_many_args_at_most)
3576 << FnKind
3577 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3578 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3579 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003580
3581 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003582 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003583 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3584 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003585
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003586 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003587 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003588 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003589 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003590 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003591 SmallVector<Expr *, 8> AllArgs;
Richard Smith55ce3522012-06-25 20:30:08 +00003592 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3593
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003594 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003595 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003596 if (Invalid)
3597 return true;
3598 unsigned TotalNumArgs = AllArgs.size();
3599 for (unsigned i = 0; i < TotalNumArgs; ++i)
3600 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003601
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003602 return false;
3603}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003604
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003605bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3606 FunctionDecl *FDecl,
3607 const FunctionProtoType *Proto,
3608 unsigned FirstProtoArg,
3609 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003610 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003611 VariadicCallType CallType,
3612 bool AllowExplicit) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003613 unsigned NumArgsInProto = Proto->getNumArgs();
3614 unsigned NumArgsToCheck = NumArgs;
3615 bool Invalid = false;
3616 if (NumArgs != NumArgsInProto)
3617 // Use default arguments for missing arguments
3618 NumArgsToCheck = NumArgsInProto;
3619 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003620 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003621 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003622 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003623
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003624 Expr *Arg;
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003625 ParmVarDecl *Param;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003626 if (ArgIx < NumArgs) {
3627 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003628
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003629 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedman3164fb12009-03-22 22:00:50 +00003630 ProtoArgType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003631 diag::err_call_incomplete_argument, Arg))
Eli Friedman3164fb12009-03-22 22:00:50 +00003632 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003633
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003634 // Pass the argument
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003635 Param = 0;
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003636 if (FDecl && i < FDecl->getNumParams())
3637 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003638
John McCall4124c492011-10-17 18:40:02 +00003639 // Strip the unbridged-cast placeholder expression off, if applicable.
3640 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3641 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3642 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3643 Arg = stripARCUnbridgedCast(Arg);
3644
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003645 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003646 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003647 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3648 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003649 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003650 SourceLocation(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00003651 Owned(Arg),
3652 /*TopLevelOfInitList=*/false,
3653 AllowExplicit);
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003654 if (ArgE.isInvalid())
3655 return true;
3656
3657 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003658 } else {
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003659 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003660
John McCalldadc5752010-08-24 06:29:42 +00003661 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003662 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003663 if (ArgExpr.isInvalid())
3664 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003665
Anders Carlsson355933d2009-08-25 03:49:14 +00003666 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003667 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003668
3669 // Check for array bounds violations for each argument to the call. This
3670 // check only triggers warnings when the argument isn't a more complex Expr
3671 // with its own checking, such as a BinaryOperator.
3672 CheckArrayAccess(Arg);
3673
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003674 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3675 CheckStaticArrayArgument(CallLoc, Param, Arg);
3676
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003677 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003678 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003679
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003680 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003681 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003682 // Assume that extern "C" functions with variadic arguments that
3683 // return __unknown_anytype aren't *really* variadic.
3684 if (Proto->getResultType() == Context.UnknownAnyTy &&
3685 FDecl && FDecl->isExternC()) {
3686 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3687 ExprResult arg;
3688 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3689 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3690 else
3691 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3692 Invalid |= arg.isInvalid();
3693 AllArgs.push_back(arg.take());
3694 }
3695
3696 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3697 } else {
3698 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003699 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3700 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003701 Invalid |= Arg.isInvalid();
3702 AllArgs.push_back(Arg.take());
3703 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003704 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003705
3706 // Check for array bounds violations.
3707 for (unsigned i = ArgIx; i != NumArgs; ++i)
3708 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003709 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003710 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003711}
3712
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003713static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3714 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3715 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3716 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3717 << ATL->getLocalSourceRange();
3718}
3719
3720/// CheckStaticArrayArgument - If the given argument corresponds to a static
3721/// array parameter, check that it is non-null, and that if it is formed by
3722/// array-to-pointer decay, the underlying array is sufficiently large.
3723///
3724/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3725/// array type derivation, then for each call to the function, the value of the
3726/// corresponding actual argument shall provide access to the first element of
3727/// an array with at least as many elements as specified by the size expression.
3728void
3729Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3730 ParmVarDecl *Param,
3731 const Expr *ArgExpr) {
3732 // Static array parameters are not supported in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003733 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003734 return;
3735
3736 QualType OrigTy = Param->getOriginalType();
3737
3738 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3739 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3740 return;
3741
3742 if (ArgExpr->isNullPointerConstant(Context,
3743 Expr::NPC_NeverValueDependent)) {
3744 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3745 DiagnoseCalleeStaticArrayParam(*this, Param);
3746 return;
3747 }
3748
3749 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3750 if (!CAT)
3751 return;
3752
3753 const ConstantArrayType *ArgCAT =
3754 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3755 if (!ArgCAT)
3756 return;
3757
3758 if (ArgCAT->getSize().ult(CAT->getSize())) {
3759 Diag(CallLoc, diag::warn_static_array_too_small)
3760 << ArgExpr->getSourceRange()
3761 << (unsigned) ArgCAT->getSize().getZExtValue()
3762 << (unsigned) CAT->getSize().getZExtValue();
3763 DiagnoseCalleeStaticArrayParam(*this, Param);
3764 }
3765}
3766
John McCall2979fe02011-04-12 00:42:48 +00003767/// Given a function expression of unknown-any type, try to rebuild it
3768/// to have a function type.
3769static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3770
Steve Naroff83895f72007-09-16 03:34:24 +00003771/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003772/// This provides the location of the left/right parens and a list of comma
3773/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003774ExprResult
John McCallb268a282010-08-23 23:25:46 +00003775Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003776 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003777 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003778 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003779 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003780 if (Result.isInvalid()) return ExprError();
3781 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003782
David Blaikiebbafb8a2012-03-11 07:00:24 +00003783 if (getLangOpts().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003784 // If this is a pseudo-destructor expression, build the call immediately.
3785 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003786 if (!ArgExprs.empty()) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003787 // Pseudo-destructor calls should not have any arguments.
3788 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003789 << FixItHint::CreateRemoval(
Benjamin Kramerc215e762012-08-24 11:54:20 +00003790 SourceRange(ArgExprs[0]->getLocStart(),
3791 ArgExprs.back()->getLocEnd()));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003792 }
Mike Stump11289f42009-09-09 15:08:12 +00003793
Benjamin Kramerc215e762012-08-24 11:54:20 +00003794 return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3795 Context.VoidTy, VK_RValue,
3796 RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003797 }
Mike Stump11289f42009-09-09 15:08:12 +00003798
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003799 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003800 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003801 // FIXME: Will need to cache the results of name lookup (including ADL) in
3802 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003803 bool Dependent = false;
3804 if (Fn->isTypeDependent())
3805 Dependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003806 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003807 Dependent = true;
3808
Peter Collingbourne41f85462011-02-09 21:07:24 +00003809 if (Dependent) {
3810 if (ExecConfig) {
3811 return Owned(new (Context) CUDAKernelCallExpr(
Benjamin Kramerc215e762012-08-24 11:54:20 +00003812 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003813 Context.DependentTy, VK_RValue, RParenLoc));
3814 } else {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003815 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003816 Context.DependentTy, VK_RValue,
3817 RParenLoc));
3818 }
3819 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003820
3821 // Determine whether this is a call to an object (C++ [over.call.object]).
3822 if (Fn->getType()->isRecordType())
Benjamin Kramerc215e762012-08-24 11:54:20 +00003823 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3824 ArgExprs.data(),
3825 ArgExprs.size(), RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003826
John McCall2979fe02011-04-12 00:42:48 +00003827 if (Fn->getType() == Context.UnknownAnyTy) {
3828 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3829 if (result.isInvalid()) return ExprError();
3830 Fn = result.take();
3831 }
3832
John McCall0009fcc2011-04-26 20:42:42 +00003833 if (Fn->getType() == Context.BoundMemberTy) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003834 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3835 ArgExprs.size(), RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003836 }
John McCall0009fcc2011-04-26 20:42:42 +00003837 }
John McCall10eae182009-11-30 22:42:35 +00003838
John McCall0009fcc2011-04-26 20:42:42 +00003839 // Check for overloaded calls. This can happen even in C due to extensions.
3840 if (Fn->getType() == Context.OverloadTy) {
3841 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3842
Douglas Gregorcda22702011-10-13 18:10:35 +00003843 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregorf4a06c22011-10-13 18:26:27 +00003844 if (!find.HasFormOfMemberPointer) {
John McCall0009fcc2011-04-26 20:42:42 +00003845 OverloadExpr *ovl = find.Expression;
3846 if (isa<UnresolvedLookupExpr>(ovl)) {
3847 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
Benjamin Kramerc215e762012-08-24 11:54:20 +00003848 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3849 ArgExprs.size(), RParenLoc, ExecConfig);
John McCall0009fcc2011-04-26 20:42:42 +00003850 } else {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003851 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3852 ArgExprs.size(), RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003853 }
3854 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003855 }
3856
Douglas Gregore254f902009-02-04 00:32:51 +00003857 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregord8fb1e32011-12-01 01:37:36 +00003858 if (Fn->getType() == Context.UnknownAnyTy) {
3859 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3860 if (result.isInvalid()) return ExprError();
3861 Fn = result.take();
3862 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003863
Eli Friedmane14b1992009-12-26 03:35:45 +00003864 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003865
John McCall57500772009-12-16 12:17:52 +00003866 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003867 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3868 if (UnOp->getOpcode() == UO_AddrOf)
3869 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3870
John McCall57500772009-12-16 12:17:52 +00003871 if (isa<DeclRefExpr>(NakedFn))
3872 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003873 else if (isa<MemberExpr>(NakedFn))
3874 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003875
Benjamin Kramerc215e762012-08-24 11:54:20 +00003876 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
3877 ArgExprs.size(), RParenLoc, ExecConfig,
3878 IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003879}
3880
3881ExprResult
3882Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003883 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003884 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3885 if (!ConfigDecl)
3886 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3887 << "cudaConfigureCall");
3888 QualType ConfigQTy = ConfigDecl->getType();
3889
3890 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCall113bee02012-03-10 09:33:50 +00003891 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedmanfa0df832012-02-02 03:46:19 +00003892 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003893
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003894 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3895 /*IsExecConfig=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003896}
3897
Tanya Lattner55808c12011-06-04 00:47:47 +00003898/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3899///
3900/// __builtin_astype( value, dst type )
3901///
Richard Trieuba63ce62011-09-09 01:45:06 +00003902ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003903 SourceLocation BuiltinLoc,
3904 SourceLocation RParenLoc) {
3905 ExprValueKind VK = VK_RValue;
3906 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003907 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3908 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003909 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3910 return ExprError(Diag(BuiltinLoc,
3911 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003912 << DstTy
3913 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003914 << E->getSourceRange());
3915 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003916 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003917}
3918
John McCall57500772009-12-16 12:17:52 +00003919/// BuildResolvedCallExpr - Build a call to a resolved expression,
3920/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003921/// unary-convert to an expression of function-pointer or
3922/// block-pointer type.
3923///
3924/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003925ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003926Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3927 SourceLocation LParenLoc,
3928 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003929 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003930 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00003931 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3932
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003933 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003934 ExprResult Result = UsualUnaryConversions(Fn);
3935 if (Result.isInvalid())
3936 return ExprError();
3937 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003938
Chris Lattner08464942007-12-28 05:29:59 +00003939 // Make the call expr early, before semantic checks. This guarantees cleanup
3940 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003941 CallExpr *TheCall;
Eric Christopher13586ab2012-05-30 01:14:28 +00003942 if (Config)
Peter Collingbourne41f85462011-02-09 21:07:24 +00003943 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3944 cast<CallExpr>(Config),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003945 llvm::makeArrayRef(Args,NumArgs),
Peter Collingbourne41f85462011-02-09 21:07:24 +00003946 Context.BoolTy,
3947 VK_RValue,
3948 RParenLoc);
Eric Christopher13586ab2012-05-30 01:14:28 +00003949 else
Peter Collingbourne41f85462011-02-09 21:07:24 +00003950 TheCall = new (Context) CallExpr(Context, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003951 llvm::makeArrayRef(Args, NumArgs),
Peter Collingbourne41f85462011-02-09 21:07:24 +00003952 Context.BoolTy,
3953 VK_RValue,
3954 RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003955
John McCallbebede42011-02-26 05:39:39 +00003956 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3957
3958 // Bail out early if calling a builtin with custom typechecking.
3959 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3960 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3961
John McCall31996342011-04-07 08:22:57 +00003962 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003963 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003964 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003965 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3966 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003967 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003968 if (FuncT == 0)
3969 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3970 << Fn->getType() << Fn->getSourceRange());
3971 } else if (const BlockPointerType *BPT =
3972 Fn->getType()->getAs<BlockPointerType>()) {
3973 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3974 } else {
John McCall31996342011-04-07 08:22:57 +00003975 // Handle calls to expressions of unknown-any type.
3976 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003977 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003978 if (rewrite.isInvalid()) return ExprError();
3979 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003980 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003981 goto retry;
3982 }
3983
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003984 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3985 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003986 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003987
David Blaikiebbafb8a2012-03-11 07:00:24 +00003988 if (getLangOpts().CUDA) {
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003989 if (Config) {
3990 // CUDA: Kernel calls must be to global functions
3991 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3992 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3993 << FDecl->getName() << Fn->getSourceRange());
3994
3995 // CUDA: Kernel function must have 'void' return type
3996 if (!FuncT->getResultType()->isVoidType())
3997 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3998 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00003999 } else {
4000 // CUDA: Calls to global functions must be configured
4001 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4002 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4003 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004004 }
4005 }
4006
Eli Friedman3164fb12009-03-22 22:00:50 +00004007 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004008 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004009 Fn->getLocStart(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004010 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004011 return ExprError();
4012
Chris Lattner08464942007-12-28 05:29:59 +00004013 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004014 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004015 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004016
Richard Smith55ce3522012-06-25 20:30:08 +00004017 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4018 if (Proto) {
John McCallb268a282010-08-23 23:25:46 +00004019 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00004020 RParenLoc, IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004021 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004022 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004023 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004024
Douglas Gregord8e97de2009-04-02 15:37:10 +00004025 if (FDecl) {
4026 // Check if we have too few/too many template arguments, based
4027 // on our knowledge of the function definition.
4028 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004029 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Richard Smith55ce3522012-06-25 20:30:08 +00004030 Proto = Def->getType()->getAs<FunctionProtoType>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00004031 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004032 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4033 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004034 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004035
4036 // If the function we're calling isn't a function prototype, but we have
4037 // a function prototype from a prior declaratiom, use that prototype.
4038 if (!FDecl->hasPrototype())
4039 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004040 }
4041
Steve Naroff0b661582007-08-28 23:30:39 +00004042 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004043 for (unsigned i = 0; i != NumArgs; i++) {
4044 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004045
4046 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004047 InitializedEntity Entity
4048 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00004049 Proto->getArgType(i),
4050 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00004051 ExprResult ArgE = PerformCopyInitialization(Entity,
4052 SourceLocation(),
4053 Owned(Arg));
4054 if (ArgE.isInvalid())
4055 return true;
4056
4057 Arg = ArgE.takeAs<Expr>();
4058
4059 } else {
John Wiegley01296292011-04-08 18:41:53 +00004060 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4061
4062 if (ArgE.isInvalid())
4063 return true;
4064
4065 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00004066 }
4067
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004068 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor83025412010-10-26 05:45:40 +00004069 Arg->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004070 diag::err_call_incomplete_argument, Arg))
Douglas Gregor83025412010-10-26 05:45:40 +00004071 return ExprError();
4072
Chris Lattner08464942007-12-28 05:29:59 +00004073 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004074 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004075 }
Chris Lattner08464942007-12-28 05:29:59 +00004076
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004077 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4078 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004079 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4080 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004081
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004082 // Check for sentinels
4083 if (NDecl)
4084 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004085
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004086 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004087 if (FDecl) {
Richard Smith55ce3522012-06-25 20:30:08 +00004088 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004089 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004090
John McCallbebede42011-02-26 05:39:39 +00004091 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004092 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004093 } else if (NDecl) {
Richard Smith55ce3522012-06-25 20:30:08 +00004094 if (CheckBlockCall(NDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004095 return ExprError();
4096 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004097
John McCallb268a282010-08-23 23:25:46 +00004098 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004099}
4100
John McCalldadc5752010-08-24 06:29:42 +00004101ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004102Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004103 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004104 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004105 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004106 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004107
4108 TypeSourceInfo *TInfo;
4109 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4110 if (!TInfo)
4111 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4112
John McCallb268a282010-08-23 23:25:46 +00004113 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004114}
4115
John McCalldadc5752010-08-24 06:29:42 +00004116ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004117Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00004118 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004119 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004120
Eli Friedman37a186d2008-05-20 05:22:08 +00004121 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004122 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004123 diag::err_illegal_decl_array_incomplete_type,
4124 SourceRange(LParenLoc,
4125 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004126 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004127 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004128 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00004129 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004130 } else if (!literalType->isDependentType() &&
4131 RequireCompleteType(LParenLoc, literalType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004132 diag::err_typecheck_decl_incomplete_type,
4133 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004134 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004135
Douglas Gregor85dabae2009-12-16 01:38:02 +00004136 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004137 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004138 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00004139 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl0501c632012-02-12 16:37:36 +00004140 SourceRange(LParenLoc, RParenLoc),
4141 /*InitList=*/true);
Richard Trieuba63ce62011-09-09 01:45:06 +00004142 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004143 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4144 &literalType);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004145 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004146 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004147 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004148
Chris Lattner79413952008-12-04 23:50:19 +00004149 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004150 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00004151 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004152 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004153 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004154
John McCall7decc9e2010-11-18 06:31:45 +00004155 // In C, compound literals are l-values for some reason.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004156 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00004157
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00004158 return MaybeBindToTemporary(
4159 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00004160 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004161}
4162
John McCalldadc5752010-08-24 06:29:42 +00004163ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004164Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004165 SourceLocation RBraceLoc) {
John McCall526ab472011-10-25 17:37:35 +00004166 // Immediately handle non-overload placeholders. Overloads can be
4167 // resolved contextually, but everything else here can't.
Benjamin Kramerc215e762012-08-24 11:54:20 +00004168 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4169 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4170 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall526ab472011-10-25 17:37:35 +00004171
4172 // Ignore failures; dropping the entire initializer list because
4173 // of one failure would be terrible for indexing/etc.
4174 if (result.isInvalid()) continue;
4175
Benjamin Kramerc215e762012-08-24 11:54:20 +00004176 InitArgList[I] = result.take();
John McCall526ab472011-10-25 17:37:35 +00004177 }
4178 }
4179
Steve Naroff30d242c2007-09-15 18:49:24 +00004180 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004181 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004182
Benjamin Kramerc215e762012-08-24 11:54:20 +00004183 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4184 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004185 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004186 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004187}
4188
John McCallcd78e802011-09-10 01:16:55 +00004189/// Do an explicit extend of the given block pointer if we're in ARC.
4190static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4191 assert(E.get()->getType()->isBlockPointerType());
4192 assert(E.get()->isRValue());
4193
4194 // Only do this in an r-value context.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004195 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallcd78e802011-09-10 01:16:55 +00004196
4197 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00004198 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00004199 /*base path*/ 0, VK_RValue);
4200 S.ExprNeedsCleanups = true;
4201}
4202
4203/// Prepare a conversion of the given expression to an ObjC object
4204/// pointer type.
4205CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4206 QualType type = E.get()->getType();
4207 if (type->isObjCObjectPointerType()) {
4208 return CK_BitCast;
4209 } else if (type->isBlockPointerType()) {
4210 maybeExtendBlockObject(*this, E);
4211 return CK_BlockPointerToObjCPointerCast;
4212 } else {
4213 assert(type->isPointerType());
4214 return CK_CPointerToObjCPointerCast;
4215 }
4216}
4217
John McCalld7646252010-11-14 08:17:51 +00004218/// Prepares for a scalar cast, performing all the necessary stages
4219/// except the final cast and returning the kind required.
John McCall9776e432011-10-06 23:25:11 +00004220CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00004221 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4222 // Also, callers should have filtered out the invalid cases with
4223 // pointers. Everything else should be possible.
4224
John Wiegley01296292011-04-08 18:41:53 +00004225 QualType SrcTy = Src.get()->getType();
John McCall9776e432011-10-06 23:25:11 +00004226 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004227 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004228
John McCall9320b872011-09-09 05:25:32 +00004229 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00004230 case Type::STK_MemberPointer:
4231 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004232
John McCall9320b872011-09-09 05:25:32 +00004233 case Type::STK_CPointer:
4234 case Type::STK_BlockPointer:
4235 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004236 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004237 case Type::STK_CPointer:
4238 return CK_BitCast;
4239 case Type::STK_BlockPointer:
4240 return (SrcKind == Type::STK_BlockPointer
4241 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4242 case Type::STK_ObjCObjectPointer:
4243 if (SrcKind == Type::STK_ObjCObjectPointer)
4244 return CK_BitCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004245 if (SrcKind == Type::STK_CPointer)
John McCall9320b872011-09-09 05:25:32 +00004246 return CK_CPointerToObjCPointerCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004247 maybeExtendBlockObject(*this, Src);
4248 return CK_BlockPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00004249 case Type::STK_Bool:
4250 return CK_PointerToBoolean;
4251 case Type::STK_Integral:
4252 return CK_PointerToIntegral;
4253 case Type::STK_Floating:
4254 case Type::STK_FloatingComplex:
4255 case Type::STK_IntegralComplex:
4256 case Type::STK_MemberPointer:
4257 llvm_unreachable("illegal cast from pointer");
4258 }
David Blaikie8a40f702012-01-17 06:56:22 +00004259 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004260
John McCall8cb679e2010-11-15 09:13:47 +00004261 case Type::STK_Bool: // casting from bool is like casting from an integer
4262 case Type::STK_Integral:
4263 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004264 case Type::STK_CPointer:
4265 case Type::STK_ObjCObjectPointer:
4266 case Type::STK_BlockPointer:
John McCall9776e432011-10-06 23:25:11 +00004267 if (Src.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00004268 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004269 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004270 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004271 case Type::STK_Bool:
4272 return CK_IntegralToBoolean;
4273 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004274 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004275 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004276 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004277 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004278 Src = ImpCastExprToType(Src.take(),
4279 DestTy->castAs<ComplexType>()->getElementType(),
4280 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004281 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004282 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004283 Src = ImpCastExprToType(Src.take(),
4284 DestTy->castAs<ComplexType>()->getElementType(),
4285 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00004286 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004287 case Type::STK_MemberPointer:
4288 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004289 }
David Blaikie8a40f702012-01-17 06:56:22 +00004290 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004291
John McCall8cb679e2010-11-15 09:13:47 +00004292 case Type::STK_Floating:
4293 switch (DestTy->getScalarTypeKind()) {
4294 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004295 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004296 case Type::STK_Bool:
4297 return CK_FloatingToBoolean;
4298 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004299 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004300 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004301 Src = ImpCastExprToType(Src.take(),
4302 DestTy->castAs<ComplexType>()->getElementType(),
4303 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004304 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004305 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004306 Src = ImpCastExprToType(Src.take(),
4307 DestTy->castAs<ComplexType>()->getElementType(),
4308 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00004309 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00004310 case Type::STK_CPointer:
4311 case Type::STK_ObjCObjectPointer:
4312 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004313 llvm_unreachable("valid float->pointer cast?");
4314 case Type::STK_MemberPointer:
4315 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004316 }
David Blaikie8a40f702012-01-17 06:56:22 +00004317 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004318
John McCall8cb679e2010-11-15 09:13:47 +00004319 case Type::STK_FloatingComplex:
4320 switch (DestTy->getScalarTypeKind()) {
4321 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004322 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004323 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004324 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004325 case Type::STK_Floating: {
John McCall9776e432011-10-06 23:25:11 +00004326 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4327 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004328 return CK_FloatingComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004329 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004330 return CK_FloatingCast;
4331 }
John McCall8cb679e2010-11-15 09:13:47 +00004332 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004333 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004334 case Type::STK_Integral:
John McCall9776e432011-10-06 23:25:11 +00004335 Src = ImpCastExprToType(Src.take(),
4336 SrcTy->castAs<ComplexType>()->getElementType(),
4337 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004338 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00004339 case Type::STK_CPointer:
4340 case Type::STK_ObjCObjectPointer:
4341 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004342 llvm_unreachable("valid complex float->pointer cast?");
4343 case Type::STK_MemberPointer:
4344 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004345 }
David Blaikie8a40f702012-01-17 06:56:22 +00004346 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004347
John McCall8cb679e2010-11-15 09:13:47 +00004348 case Type::STK_IntegralComplex:
4349 switch (DestTy->getScalarTypeKind()) {
4350 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004351 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004352 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004353 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004354 case Type::STK_Integral: {
John McCall9776e432011-10-06 23:25:11 +00004355 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4356 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004357 return CK_IntegralComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004358 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004359 return CK_IntegralCast;
4360 }
John McCall8cb679e2010-11-15 09:13:47 +00004361 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004362 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004363 case Type::STK_Floating:
John McCall9776e432011-10-06 23:25:11 +00004364 Src = ImpCastExprToType(Src.take(),
4365 SrcTy->castAs<ComplexType>()->getElementType(),
4366 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004367 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00004368 case Type::STK_CPointer:
4369 case Type::STK_ObjCObjectPointer:
4370 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004371 llvm_unreachable("valid complex int->pointer cast?");
4372 case Type::STK_MemberPointer:
4373 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004374 }
David Blaikie8a40f702012-01-17 06:56:22 +00004375 llvm_unreachable("Should have returned before this");
Anders Carlsson094c4592009-10-18 18:12:03 +00004376 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004377
John McCalld7646252010-11-14 08:17:51 +00004378 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004379}
4380
Anders Carlsson525b76b2009-10-16 02:48:28 +00004381bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004382 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004383 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004384
Anders Carlssonde71adf2007-11-27 05:51:55 +00004385 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004386 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004387 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004388 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004389 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004390 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004391 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004392 } else
4393 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004394 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004395 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004396
John McCalle3027922010-08-25 11:45:40 +00004397 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004398 return false;
4399}
4400
John Wiegley01296292011-04-08 18:41:53 +00004401ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4402 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004403 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004404
Anders Carlsson43d70f82009-10-16 05:23:41 +00004405 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004406
Nate Begemanc8961a42009-06-27 22:05:55 +00004407 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4408 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004409 // In OpenCL, casts between vectors of different types are not allowed.
4410 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004411 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004412 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikiebbafb8a2012-03-11 07:00:24 +00004413 || (getLangOpts().OpenCL &&
Tobias Grosser766bcc22011-09-22 13:03:14 +00004414 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004415 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004416 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004417 return ExprError();
4418 }
John McCalle3027922010-08-25 11:45:40 +00004419 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004420 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004421 }
4422
Nate Begemanbd956c42009-06-28 02:36:38 +00004423 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004424 // conversion will take place first from scalar to elt type, and then
4425 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004426 if (SrcTy->isPointerType())
4427 return Diag(R.getBegin(),
4428 diag::err_invalid_conversion_between_vector_and_scalar)
4429 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004430
4431 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004432 ExprResult CastExprRes = Owned(CastExpr);
John McCall9776e432011-10-06 23:25:11 +00004433 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley01296292011-04-08 18:41:53 +00004434 if (CastExprRes.isInvalid())
4435 return ExprError();
4436 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004437
John McCalle3027922010-08-25 11:45:40 +00004438 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004439 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004440}
4441
John McCalldadc5752010-08-24 06:29:42 +00004442ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004443Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4444 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004445 SourceLocation RParenLoc, Expr *CastExpr) {
4446 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004447 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004448
Richard Trieuba63ce62011-09-09 01:45:06 +00004449 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004450 if (D.isInvalidType())
4451 return ExprError();
4452
David Blaikiebbafb8a2012-03-11 07:00:24 +00004453 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004454 // Check that there are no default arguments (C++ only).
4455 CheckExtraCXXDefaultArguments(D);
4456 }
4457
John McCall42856de2011-10-01 05:17:03 +00004458 checkUnusedDeclAttributes(D);
4459
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004460 QualType castType = castTInfo->getType();
4461 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004462
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004463 bool isVectorLiteral = false;
4464
4465 // Check for an altivec or OpenCL literal,
4466 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004467 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4468 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004469 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004470 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004471 if (PLE && PLE->getNumExprs() == 0) {
4472 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4473 return ExprError();
4474 }
4475 if (PE || PLE->getNumExprs() == 1) {
4476 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4477 if (!E->getType()->isVectorType())
4478 isVectorLiteral = true;
4479 }
4480 else
4481 isVectorLiteral = true;
4482 }
4483
4484 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4485 // then handle it as such.
4486 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004487 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004488
Nate Begeman5ec4b312009-08-10 23:49:36 +00004489 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004490 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4491 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004492 if (isa<ParenListExpr>(CastExpr)) {
4493 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004494 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004495 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004496 }
John McCallebe54742010-01-15 18:56:44 +00004497
Richard Trieuba63ce62011-09-09 01:45:06 +00004498 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004499}
4500
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004501ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4502 SourceLocation RParenLoc, Expr *E,
4503 TypeSourceInfo *TInfo) {
4504 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4505 "Expected paren or paren list expression");
4506
4507 Expr **exprs;
4508 unsigned numExprs;
4509 Expr *subExpr;
4510 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4511 exprs = PE->getExprs();
4512 numExprs = PE->getNumExprs();
4513 } else {
4514 subExpr = cast<ParenExpr>(E)->getSubExpr();
4515 exprs = &subExpr;
4516 numExprs = 1;
4517 }
4518
4519 QualType Ty = TInfo->getType();
4520 assert(Ty->isVectorType() && "Expected vector type");
4521
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004522 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004523 const VectorType *VTy = Ty->getAs<VectorType>();
4524 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4525
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004526 // '(...)' form of vector initialization in AltiVec: the number of
4527 // initializers must be one or must match the size of the vector.
4528 // If a single value is specified in the initializer then it will be
4529 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004530 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004531 // The number of initializers must be one or must match the size of the
4532 // vector. If a single value is specified in the initializer then it will
4533 // be replicated to all the components of the vector
4534 if (numExprs == 1) {
4535 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004536 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4537 if (Literal.isInvalid())
4538 return ExprError();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004539 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004540 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004541 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4542 }
4543 else if (numExprs < numElems) {
4544 Diag(E->getExprLoc(),
4545 diag::err_incorrect_number_of_vector_initializers);
4546 return ExprError();
4547 }
4548 else
Benjamin Kramer8001f742012-02-14 12:06:21 +00004549 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004550 }
Tanya Lattner83559382011-07-15 23:07:01 +00004551 else {
4552 // For OpenCL, when the number of initializers is a single value,
4553 // it will be replicated to all components of the vector.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004554 if (getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00004555 VTy->getVectorKind() == VectorType::GenericVector &&
4556 numExprs == 1) {
4557 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004558 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4559 if (Literal.isInvalid())
4560 return ExprError();
Tanya Lattner83559382011-07-15 23:07:01 +00004561 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004562 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner83559382011-07-15 23:07:01 +00004563 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4564 }
4565
Benjamin Kramer8001f742012-02-14 12:06:21 +00004566 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner83559382011-07-15 23:07:01 +00004567 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004568 // FIXME: This means that pretty-printing the final AST will produce curly
4569 // braces instead of the original commas.
4570 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004571 initExprs, RParenLoc);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004572 initE->setType(Ty);
4573 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4574}
4575
Sebastian Redla9351792012-02-11 23:51:47 +00004576/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4577/// the ParenListExpr into a sequence of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004578ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004579Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4580 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004581 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004582 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004583
John McCalldadc5752010-08-24 06:29:42 +00004584 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004585
Nate Begeman5ec4b312009-08-10 23:49:36 +00004586 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004587 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4588 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004589
John McCallb268a282010-08-23 23:25:46 +00004590 if (Result.isInvalid()) return ExprError();
4591
4592 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004593}
4594
Sebastian Redla9351792012-02-11 23:51:47 +00004595ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4596 SourceLocation R,
4597 MultiExprArg Val) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00004598 assert(Val.data() != 0 && "ActOnParenOrParenListExpr() missing expr list");
4599 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004600 return Owned(expr);
4601}
4602
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004603/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004604/// constant and the other is not a pointer. Returns true if a diagnostic is
4605/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004606bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004607 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004608 Expr *NullExpr = LHSExpr;
4609 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004610 Expr::NullPointerConstantKind NullKind =
4611 NullExpr->isNullPointerConstant(Context,
4612 Expr::NPC_ValueDependentIsNotNull);
4613
4614 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004615 NullExpr = RHSExpr;
4616 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004617 NullKind =
4618 NullExpr->isNullPointerConstant(Context,
4619 Expr::NPC_ValueDependentIsNotNull);
4620 }
4621
4622 if (NullKind == Expr::NPCK_NotNull)
4623 return false;
4624
David Blaikie1c7c8f72012-08-08 17:33:31 +00004625 if (NullKind == Expr::NPCK_ZeroExpression)
4626 return false;
4627
4628 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004629 // In this case, check to make sure that we got here from a "NULL"
4630 // string in the source code.
4631 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004632 SourceLocation loc = NullExpr->getExprLoc();
4633 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004634 return false;
4635 }
4636
4637 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4638 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4639 << NonPointerExpr->getType() << DiagType
4640 << NonPointerExpr->getSourceRange();
4641 return true;
4642}
4643
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004644/// \brief Return false if the condition expression is valid, true otherwise.
4645static bool checkCondition(Sema &S, Expr *Cond) {
4646 QualType CondTy = Cond->getType();
4647
4648 // C99 6.5.15p2
4649 if (CondTy->isScalarType()) return false;
4650
4651 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004652 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004653 return false;
4654
4655 // Emit the proper error message.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004656 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004657 diag::err_typecheck_cond_expect_scalar :
4658 diag::err_typecheck_cond_expect_scalar_or_vector)
4659 << CondTy;
4660 return true;
4661}
4662
4663/// \brief Return false if the two expressions can be converted to a vector,
4664/// true otherwise
4665static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4666 ExprResult &RHS,
4667 QualType CondTy) {
4668 // Both operands should be of scalar type.
4669 if (!LHS.get()->getType()->isScalarType()) {
4670 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4671 << CondTy;
4672 return true;
4673 }
4674 if (!RHS.get()->getType()->isScalarType()) {
4675 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4676 << CondTy;
4677 return true;
4678 }
4679
4680 // Implicity convert these scalars to the type of the condition.
4681 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4682 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4683 return false;
4684}
4685
4686/// \brief Handle when one or both operands are void type.
4687static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4688 ExprResult &RHS) {
4689 Expr *LHSExpr = LHS.get();
4690 Expr *RHSExpr = RHS.get();
4691
4692 if (!LHSExpr->getType()->isVoidType())
4693 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4694 << RHSExpr->getSourceRange();
4695 if (!RHSExpr->getType()->isVoidType())
4696 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4697 << LHSExpr->getSourceRange();
4698 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4699 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4700 return S.Context.VoidTy;
4701}
4702
4703/// \brief Return false if the NullExpr can be promoted to PointerTy,
4704/// true otherwise.
4705static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4706 QualType PointerTy) {
4707 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4708 !NullExpr.get()->isNullPointerConstant(S.Context,
4709 Expr::NPC_ValueDependentIsNull))
4710 return true;
4711
4712 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4713 return false;
4714}
4715
4716/// \brief Checks compatibility between two pointers and return the resulting
4717/// type.
4718static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4719 ExprResult &RHS,
4720 SourceLocation Loc) {
4721 QualType LHSTy = LHS.get()->getType();
4722 QualType RHSTy = RHS.get()->getType();
4723
4724 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4725 // Two identical pointers types are always compatible.
4726 return LHSTy;
4727 }
4728
4729 QualType lhptee, rhptee;
4730
4731 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004732 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4733 lhptee = LHSBTy->getPointeeType();
4734 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004735 } else {
John McCall9320b872011-09-09 05:25:32 +00004736 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4737 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004738 }
4739
Eli Friedman57a75392012-04-05 22:30:04 +00004740 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4741 // differently qualified versions of compatible types, the result type is
4742 // a pointer to an appropriately qualified version of the composite
4743 // type.
4744
4745 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4746 // clause doesn't make sense for our extensions. E.g. address space 2 should
4747 // be incompatible with address space 3: they may live on different devices or
4748 // anything.
4749 Qualifiers lhQual = lhptee.getQualifiers();
4750 Qualifiers rhQual = rhptee.getQualifiers();
4751
4752 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4753 lhQual.removeCVRQualifiers();
4754 rhQual.removeCVRQualifiers();
4755
4756 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4757 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4758
4759 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4760
4761 if (CompositeTy.isNull()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004762 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4763 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4764 << RHS.get()->getSourceRange();
4765 // In this situation, we assume void* type. No especially good
4766 // reason, but this is what gcc does, and we do have to pick
4767 // to get a consistent AST.
4768 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4769 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4770 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4771 return incompatTy;
4772 }
4773
4774 // The pointer types are compatible.
Eli Friedman57a75392012-04-05 22:30:04 +00004775 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4776 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004777
Eli Friedman57a75392012-04-05 22:30:04 +00004778 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4779 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4780 return ResultTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004781}
4782
4783/// \brief Return the resulting type when the operands are both block pointers.
4784static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4785 ExprResult &LHS,
4786 ExprResult &RHS,
4787 SourceLocation Loc) {
4788 QualType LHSTy = LHS.get()->getType();
4789 QualType RHSTy = RHS.get()->getType();
4790
4791 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4792 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4793 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4794 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4795 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4796 return destType;
4797 }
4798 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4799 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4800 << RHS.get()->getSourceRange();
4801 return QualType();
4802 }
4803
4804 // We have 2 block pointer types.
4805 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4806}
4807
4808/// \brief Return the resulting type when the operands are both pointers.
4809static QualType
4810checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4811 ExprResult &RHS,
4812 SourceLocation Loc) {
4813 // get the pointer types
4814 QualType LHSTy = LHS.get()->getType();
4815 QualType RHSTy = RHS.get()->getType();
4816
4817 // get the "pointed to" types
4818 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4819 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4820
4821 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4822 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4823 // Figure out necessary qualifiers (C99 6.5.15p6)
4824 QualType destPointee
4825 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4826 QualType destType = S.Context.getPointerType(destPointee);
4827 // Add qualifiers if necessary.
4828 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4829 // Promote to void*.
4830 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4831 return destType;
4832 }
4833 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4834 QualType destPointee
4835 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4836 QualType destType = S.Context.getPointerType(destPointee);
4837 // Add qualifiers if necessary.
4838 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4839 // Promote to void*.
4840 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4841 return destType;
4842 }
4843
4844 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4845}
4846
4847/// \brief Return false if the first expression is not an integer and the second
4848/// expression is not a pointer, true otherwise.
4849static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4850 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004851 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004852 if (!PointerExpr->getType()->isPointerType() ||
4853 !Int.get()->getType()->isIntegerType())
4854 return false;
4855
Richard Trieuba63ce62011-09-09 01:45:06 +00004856 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4857 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004858
4859 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4860 << Expr1->getType() << Expr2->getType()
4861 << Expr1->getSourceRange() << Expr2->getSourceRange();
4862 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4863 CK_IntegralToPointer);
4864 return true;
4865}
4866
Richard Trieud33e46e2011-09-06 20:06:39 +00004867/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4868/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004869/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004870QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4871 ExprResult &RHS, ExprValueKind &VK,
4872 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004873 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004874
Richard Trieud33e46e2011-09-06 20:06:39 +00004875 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4876 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004877 LHS = LHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004878
Richard Trieud33e46e2011-09-06 20:06:39 +00004879 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4880 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004881 RHS = RHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004882
Sebastian Redl1a99f442009-04-16 17:51:27 +00004883 // C++ is sufficiently different to merit its own checker.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004884 if (getLangOpts().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004885 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004886
4887 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004888 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004889
John Wiegley01296292011-04-08 18:41:53 +00004890 Cond = UsualUnaryConversions(Cond.take());
4891 if (Cond.isInvalid())
4892 return QualType();
4893 LHS = UsualUnaryConversions(LHS.take());
4894 if (LHS.isInvalid())
4895 return QualType();
4896 RHS = UsualUnaryConversions(RHS.take());
4897 if (RHS.isInvalid())
4898 return QualType();
4899
4900 QualType CondTy = Cond.get()->getType();
4901 QualType LHSTy = LHS.get()->getType();
4902 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004903
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004904 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004905 if (checkCondition(*this, Cond.get()))
4906 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004907
Chris Lattnere2949f42008-01-06 22:42:25 +00004908 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004909 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004910 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004911
Nate Begemanabb5a732010-09-20 22:41:17 +00004912 // OpenCL: If the condition is a vector, and both operands are scalar,
4913 // attempt to implicity convert them to the vector type to act like the
4914 // built in select.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004915 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004916 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004917 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004918
Chris Lattnere2949f42008-01-06 22:42:25 +00004919 // If both operands have arithmetic type, do the usual arithmetic conversions
4920 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004921 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4922 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004923 if (LHS.isInvalid() || RHS.isInvalid())
4924 return QualType();
4925 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004926 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004927
Chris Lattnere2949f42008-01-06 22:42:25 +00004928 // If both operands are the same structure or union type, the result is that
4929 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004930 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4931 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004932 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004933 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004934 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004935 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004936 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004937 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004938
Chris Lattnere2949f42008-01-06 22:42:25 +00004939 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004940 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004941 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004942 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004943 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004944
Steve Naroff039ad3c2008-01-08 01:11:38 +00004945 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4946 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004947 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4948 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004949
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004950 // All objective-c pointer type analysis is done here.
4951 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4952 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004953 if (LHS.isInvalid() || RHS.isInvalid())
4954 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004955 if (!compositeType.isNull())
4956 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004957
4958
Steve Naroff05efa972009-07-01 14:36:47 +00004959 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004960 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4961 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4962 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004963
Steve Naroff05efa972009-07-01 14:36:47 +00004964 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004965 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4966 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4967 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004968
John McCalle84af4e2010-11-13 01:35:44 +00004969 // GCC compatibility: soften pointer/integer mismatch. Note that
4970 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004971 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4972 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00004973 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004974 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4975 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00004976 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00004977
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004978 // Emit a better diagnostic if one of the expressions is a null pointer
4979 // constant and the other is not a pointer type. In this case, the user most
4980 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004981 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004982 return QualType();
4983
Chris Lattnere2949f42008-01-06 22:42:25 +00004984 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004985 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004986 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4987 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004988 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004989}
4990
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004991/// FindCompositeObjCPointerType - Helper method to find composite type of
4992/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004993QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004994 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004995 QualType LHSTy = LHS.get()->getType();
4996 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004997
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004998 // Handle things like Class and struct objc_class*. Here we case the result
4999 // to the pseudo-builtin, because that will be implicitly cast back to the
5000 // redefinition type if an attempt is made to access its fields.
5001 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005002 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005003 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005004 return LHSTy;
5005 }
5006 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005007 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005008 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005009 return RHSTy;
5010 }
5011 // And the same for struct objc_object* / id
5012 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005013 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005014 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005015 return LHSTy;
5016 }
5017 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005018 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005019 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005020 return RHSTy;
5021 }
5022 // And the same for struct objc_selector* / SEL
5023 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00005024 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005025 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005026 return LHSTy;
5027 }
5028 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00005029 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005030 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005031 return RHSTy;
5032 }
5033 // Check constraints for Objective-C object pointers types.
5034 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005035
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005036 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5037 // Two identical object pointer types are always compatible.
5038 return LHSTy;
5039 }
John McCall9320b872011-09-09 05:25:32 +00005040 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5041 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005042 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005043
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005044 // If both operands are interfaces and either operand can be
5045 // assigned to the other, use that type as the composite
5046 // type. This allows
5047 // xxx ? (A*) a : (B*) b
5048 // where B is a subclass of A.
5049 //
5050 // Additionally, as for assignment, if either type is 'id'
5051 // allow silent coercion. Finally, if the types are
5052 // incompatible then make sure to use 'id' as the composite
5053 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005054
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005055 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5056 // It could return the composite type.
5057 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5058 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5059 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5060 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5061 } else if ((LHSTy->isObjCQualifiedIdType() ||
5062 RHSTy->isObjCQualifiedIdType()) &&
5063 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5064 // Need to handle "id<xx>" explicitly.
5065 // GCC allows qualified id and any Objective-C type to devolve to
5066 // id. Currently localizing to here until clear this should be
5067 // part of ObjCQualifiedIdTypesAreCompatible.
5068 compositeType = Context.getObjCIdType();
5069 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5070 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005071 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005072 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5073 ;
5074 else {
5075 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5076 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00005077 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005078 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00005079 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5080 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005081 return incompatTy;
5082 }
5083 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00005084 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5085 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005086 return compositeType;
5087 }
5088 // Check Objective-C object pointer types and 'void *'
5089 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005090 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00005091 // ARC forbids the implicit conversion of object pointers to 'void *',
5092 // so these types are not compatible.
5093 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5094 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5095 LHS = RHS = true;
5096 return QualType();
5097 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005098 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5099 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5100 QualType destPointee
5101 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5102 QualType destType = Context.getPointerType(destPointee);
5103 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005104 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005105 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005106 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005107 return destType;
5108 }
5109 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005110 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00005111 // ARC forbids the implicit conversion of object pointers to 'void *',
5112 // so these types are not compatible.
5113 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5114 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5115 LHS = RHS = true;
5116 return QualType();
5117 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005118 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5119 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5120 QualType destPointee
5121 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5122 QualType destType = Context.getPointerType(destPointee);
5123 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005124 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005125 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005126 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005127 return destType;
5128 }
5129 return QualType();
5130}
5131
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005132/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005133/// ParenRange in parentheses.
5134static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005135 const PartialDiagnostic &Note,
5136 SourceRange ParenRange) {
5137 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5138 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5139 EndLoc.isValid()) {
5140 Self.Diag(Loc, Note)
5141 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5142 << FixItHint::CreateInsertion(EndLoc, ")");
5143 } else {
5144 // We can't display the parentheses, so just show the bare note.
5145 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005146 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005147}
5148
5149static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5150 return Opc >= BO_Mul && Opc <= BO_Shr;
5151}
5152
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005153/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5154/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00005155/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5156/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005157static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00005158 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00005159 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5160 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005161 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00005162 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005163
5164 // Built-in binary operator.
5165 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5166 if (IsArithmeticOp(OP->getOpcode())) {
5167 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00005168 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005169 return true;
5170 }
5171 }
5172
5173 // Overloaded operator.
5174 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5175 if (Call->getNumArgs() != 2)
5176 return false;
5177
5178 // Make sure this is really a binary operator that is safe to pass into
5179 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5180 OverloadedOperatorKind OO = Call->getOperator();
5181 if (OO < OO_Plus || OO > OO_Arrow)
5182 return false;
5183
5184 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5185 if (IsArithmeticOp(OpKind)) {
5186 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00005187 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005188 return true;
5189 }
5190 }
5191
5192 return false;
5193}
5194
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005195static bool IsLogicOp(BinaryOperatorKind Opc) {
5196 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5197}
5198
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005199/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5200/// or is a logical expression such as (x==y) which has int type, but is
5201/// commonly interpreted as boolean.
5202static bool ExprLooksBoolean(Expr *E) {
5203 E = E->IgnoreParenImpCasts();
5204
5205 if (E->getType()->isBooleanType())
5206 return true;
5207 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5208 return IsLogicOp(OP->getOpcode());
5209 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5210 return OP->getOpcode() == UO_LNot;
5211
5212 return false;
5213}
5214
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005215/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5216/// and binary operator are mixed in a way that suggests the programmer assumed
5217/// the conditional operator has higher precedence, for example:
5218/// "int x = a + someBinaryCondition ? 1 : 2".
5219static void DiagnoseConditionalPrecedence(Sema &Self,
5220 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005221 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00005222 Expr *LHSExpr,
5223 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005224 BinaryOperatorKind CondOpcode;
5225 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005226
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005227 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005228 return;
5229 if (!ExprLooksBoolean(CondRHS))
5230 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005231
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005232 // The condition is an arithmetic binary expression, with a right-
5233 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005234
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005235 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005236 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005237 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005238
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005239 SuggestParentheses(Self, OpLoc,
5240 Self.PDiag(diag::note_precedence_conditional_silence)
5241 << BinaryOperator::getOpcodeStr(CondOpcode),
5242 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00005243
5244 SuggestParentheses(Self, OpLoc,
5245 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00005246 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005247}
5248
Steve Naroff83895f72007-09-16 03:34:24 +00005249/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005250/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005251ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005252 SourceLocation ColonLoc,
5253 Expr *CondExpr, Expr *LHSExpr,
5254 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005255 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5256 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005257 OpaqueValueExpr *opaqueValue = 0;
5258 Expr *commonExpr = 0;
5259 if (LHSExpr == 0) {
5260 commonExpr = CondExpr;
5261
5262 // We usually want to apply unary conversions *before* saving, except
5263 // in the special case of a C++ l-value conditional.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005264 if (!(getLangOpts().CPlusPlus
John McCallc07a0c72011-02-17 10:25:35 +00005265 && !commonExpr->isTypeDependent()
5266 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5267 && commonExpr->isGLValue()
5268 && commonExpr->isOrdinaryOrBitFieldObject()
5269 && RHSExpr->isOrdinaryOrBitFieldObject()
5270 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005271 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5272 if (commonRes.isInvalid())
5273 return ExprError();
5274 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005275 }
5276
5277 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5278 commonExpr->getType(),
5279 commonExpr->getValueKind(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +00005280 commonExpr->getObjectKind(),
5281 commonExpr);
John McCallc07a0c72011-02-17 10:25:35 +00005282 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005283 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005284
John McCall7decc9e2010-11-18 06:31:45 +00005285 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005286 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005287 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5288 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005289 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005290 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5291 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005292 return ExprError();
5293
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005294 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5295 RHS.get());
5296
John McCallc07a0c72011-02-17 10:25:35 +00005297 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005298 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5299 LHS.take(), ColonLoc,
5300 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005301
5302 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005303 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005304 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5305 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005306}
5307
John McCallaba90822011-01-31 23:13:11 +00005308// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005309// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005310// routine is it effectively iqnores the qualifiers on the top level pointee.
5311// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5312// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005313static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005314checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5315 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5316 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005317
Steve Naroff1f4d7272007-05-11 04:00:31 +00005318 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005319 const Type *lhptee, *rhptee;
5320 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005321 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5322 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005323
John McCallaba90822011-01-31 23:13:11 +00005324 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005325
5326 // C99 6.5.16.1p1: This following citation is common to constraints
5327 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5328 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005329 Qualifiers lq;
5330
John McCall31168b02011-06-15 23:02:42 +00005331 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5332 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5333 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5334 // Ignore lifetime for further calculation.
5335 lhq.removeObjCLifetime();
5336 rhq.removeObjCLifetime();
5337 }
5338
John McCall4fff8f62011-02-01 00:10:29 +00005339 if (!lhq.compatiblyIncludes(rhq)) {
5340 // Treat address-space mismatches as fatal. TODO: address subspaces
5341 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5342 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5343
John McCall31168b02011-06-15 23:02:42 +00005344 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005345 // and from void*.
John McCall18ce25e2012-02-08 00:46:36 +00005346 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCall31168b02011-06-15 23:02:42 +00005347 .compatiblyIncludes(
John McCall18ce25e2012-02-08 00:46:36 +00005348 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall78535952011-03-26 02:56:45 +00005349 && (lhptee->isVoidType() || rhptee->isVoidType()))
5350 ; // keep old
5351
John McCall31168b02011-06-15 23:02:42 +00005352 // Treat lifetime mismatches as fatal.
5353 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5354 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5355
John McCall4fff8f62011-02-01 00:10:29 +00005356 // For GCC compatibility, other qualifier mismatches are treated
5357 // as still compatible in C.
5358 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5359 }
Steve Naroff3f597292007-05-11 22:18:03 +00005360
Mike Stump4e1f26a2009-02-19 03:04:26 +00005361 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5362 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005363 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005364 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005365 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005366 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005367
Chris Lattner0a788432008-01-03 22:56:36 +00005368 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005369 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005370 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005371 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005372
Chris Lattner0a788432008-01-03 22:56:36 +00005373 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005374 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005375 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005376
5377 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005378 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005379 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005380 }
John McCall4fff8f62011-02-01 00:10:29 +00005381
Mike Stump4e1f26a2009-02-19 03:04:26 +00005382 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005383 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005384 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5385 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005386 // Check if the pointee types are compatible ignoring the sign.
5387 // We explicitly check for char so that we catch "char" vs
5388 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005389 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005390 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005391 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005392 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005393
Chris Lattnerec3a1562009-10-17 20:33:28 +00005394 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005395 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005396 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005397 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005398
John McCall4fff8f62011-02-01 00:10:29 +00005399 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005400 // Types are compatible ignoring the sign. Qualifier incompatibility
5401 // takes priority over sign incompatibility because the sign
5402 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005403 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005404 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005405
John McCallaba90822011-01-31 23:13:11 +00005406 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005407 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005408
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005409 // If we are a multi-level pointer, it's possible that our issue is simply
5410 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5411 // the eventual target type is the same and the pointers have the same
5412 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005413 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005414 do {
John McCall4fff8f62011-02-01 00:10:29 +00005415 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5416 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005417 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005418
John McCall4fff8f62011-02-01 00:10:29 +00005419 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005420 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005421 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005422
Eli Friedman80160bd2009-03-22 23:59:44 +00005423 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005424 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005425 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00005426 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005427 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5428 return Sema::IncompatiblePointer;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005429 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005430}
5431
John McCallaba90822011-01-31 23:13:11 +00005432/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005433/// block pointer types are compatible or whether a block and normal pointer
5434/// are compatible. It is more restrict than comparing two function pointer
5435// types.
John McCallaba90822011-01-31 23:13:11 +00005436static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005437checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5438 QualType RHSType) {
5439 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5440 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005441
Steve Naroff081c7422008-09-04 15:10:53 +00005442 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005443
Steve Naroff081c7422008-09-04 15:10:53 +00005444 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005445 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5446 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005447
John McCallaba90822011-01-31 23:13:11 +00005448 // In C++, the types have to match exactly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005449 if (S.getLangOpts().CPlusPlus)
John McCallaba90822011-01-31 23:13:11 +00005450 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005451
John McCallaba90822011-01-31 23:13:11 +00005452 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005453
Steve Naroff081c7422008-09-04 15:10:53 +00005454 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005455 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5456 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005457
Richard Trieua871b972011-09-06 20:21:22 +00005458 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005459 return Sema::IncompatibleBlockPointer;
5460
Steve Naroff081c7422008-09-04 15:10:53 +00005461 return ConvTy;
5462}
5463
John McCallaba90822011-01-31 23:13:11 +00005464/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005465/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005466static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005467checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5468 QualType RHSType) {
5469 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5470 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005471
Richard Trieua871b972011-09-06 20:21:22 +00005472 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005473 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005474 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5475 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005476 return Sema::IncompatiblePointer;
5477 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005478 }
Richard Trieua871b972011-09-06 20:21:22 +00005479 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005480 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5481 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005482 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005483 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005484 }
Richard Trieua871b972011-09-06 20:21:22 +00005485 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5486 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005487
Fariborz Jahaniane74d47e2012-01-12 22:12:08 +00005488 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5489 // make an exception for id<P>
5490 !LHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005491 return Sema::CompatiblePointerDiscardsQualifiers;
5492
Richard Trieua871b972011-09-06 20:21:22 +00005493 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005494 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005495 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005496 return Sema::IncompatibleObjCQualifiedId;
5497 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005498}
5499
John McCall29600e12010-11-16 02:32:08 +00005500Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005501Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005502 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005503 // Fake up an opaque expression. We don't actually care about what
5504 // cast operations are required, so if CheckAssignmentConstraints
5505 // adds casts to this they'll be wasted, but fortunately that doesn't
5506 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005507 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5508 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005509 CastKind K = CK_Invalid;
5510
Richard Trieua871b972011-09-06 20:21:22 +00005511 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005512}
5513
Mike Stump4e1f26a2009-02-19 03:04:26 +00005514/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5515/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005516/// pointers. Here are some objectionable examples that GCC considers warnings:
5517///
5518/// int a, *pint;
5519/// short *pshort;
5520/// struct foo *pfoo;
5521///
5522/// pint = pshort; // warning: assignment from incompatible pointer type
5523/// a = pint; // warning: assignment makes integer from pointer without a cast
5524/// pint = a; // warning: assignment makes pointer from integer without a cast
5525/// pint = pfoo; // warning: assignment from incompatible pointer type
5526///
5527/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005528/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005529///
John McCall8cb679e2010-11-15 09:13:47 +00005530/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005531Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005532Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005533 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005534 QualType RHSType = RHS.get()->getType();
5535 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005536
Chris Lattnera52c2f22008-01-04 23:18:45 +00005537 // Get canonical types. We're not formatting these types, just comparing
5538 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005539 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5540 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005541
Eli Friedman0dfb8892011-10-06 23:00:33 +00005542
John McCalle5255932011-01-31 22:28:28 +00005543 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005544 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005545 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005546 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005547 }
5548
Eli Friedman93ee5ca2012-06-16 02:19:17 +00005549 // If we have an atomic type, try a non-atomic assignment, then just add an
5550 // atomic qualification step.
David Chisnallfa35df62012-01-16 17:27:18 +00005551 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman93ee5ca2012-06-16 02:19:17 +00005552 Sema::AssignConvertType result =
5553 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5554 if (result != Compatible)
5555 return result;
5556 if (Kind != CK_NoOp)
5557 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5558 Kind = CK_NonAtomicToAtomic;
5559 return Compatible;
David Chisnallfa35df62012-01-16 17:27:18 +00005560 }
5561
Douglas Gregor6b754842008-10-28 00:22:11 +00005562 // If the left-hand side is a reference type, then we are in a
5563 // (rare!) case where we've allowed the use of references in C,
5564 // e.g., as a parameter type in a built-in function. In this case,
5565 // just make sure that the type referenced is compatible with the
5566 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005567 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005568 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005569 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5570 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005571 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005572 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005573 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005574 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005575 }
John McCalle5255932011-01-31 22:28:28 +00005576
Nate Begemanbd956c42009-06-28 02:36:38 +00005577 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5578 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005579 if (LHSType->isExtVectorType()) {
5580 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005581 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005582 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005583 // CK_VectorSplat does T -> vector T, so first cast to the
5584 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005585 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5586 if (elType != RHSType) {
John McCall9776e432011-10-06 23:25:11 +00005587 Kind = PrepareScalarCast(RHS, elType);
Richard Trieude4958f2011-09-06 20:30:53 +00005588 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005589 }
5590 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005591 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005592 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005593 }
Mike Stump11289f42009-09-09 15:08:12 +00005594
John McCalle5255932011-01-31 22:28:28 +00005595 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005596 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5597 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005598 // Allow assignments of an AltiVec vector type to an equivalent GCC
5599 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005600 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005601 Kind = CK_BitCast;
5602 return Compatible;
5603 }
5604
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005605 // If we are allowing lax vector conversions, and LHS and RHS are both
5606 // vectors, the total size only needs to be the same. This is a bitcast;
5607 // no bits are changed but the result type is different.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005608 if (getLangOpts().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005609 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005610 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005611 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005612 }
Chris Lattner881a2122008-01-04 23:32:24 +00005613 }
5614 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005615 }
Eli Friedman3360d892008-05-30 18:07:22 +00005616
John McCalle5255932011-01-31 22:28:28 +00005617 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005618 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00005619 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCall9776e432011-10-06 23:25:11 +00005620 Kind = PrepareScalarCast(RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005621 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005622 }
Eli Friedman3360d892008-05-30 18:07:22 +00005623
John McCalle5255932011-01-31 22:28:28 +00005624 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005625 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005626 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005627 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005628 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005629 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005630 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005631
John McCalle5255932011-01-31 22:28:28 +00005632 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005633 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005634 Kind = CK_IntegralToPointer; // FIXME: null?
5635 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005636 }
John McCalle5255932011-01-31 22:28:28 +00005637
5638 // C pointers are not compatible with ObjC object pointers,
5639 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005640 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005641 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005642 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005643 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005644 return Compatible;
5645 }
5646
5647 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005648 if (RHSType->isObjCClassType() &&
5649 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005650 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005651 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005652 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005653 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005654
John McCalle5255932011-01-31 22:28:28 +00005655 Kind = CK_BitCast;
5656 return IncompatiblePointer;
5657 }
5658
5659 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005660 if (RHSType->getAs<BlockPointerType>()) {
5661 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005662 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005663 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005664 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005665 }
John McCalle5255932011-01-31 22:28:28 +00005666
Steve Naroff081c7422008-09-04 15:10:53 +00005667 return Incompatible;
5668 }
5669
John McCalle5255932011-01-31 22:28:28 +00005670 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005671 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005672 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005673 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005674 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005675 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005676 }
5677
5678 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005679 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005680 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005681 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005682 }
5683
John McCalle5255932011-01-31 22:28:28 +00005684 // id -> T^
David Blaikiebbafb8a2012-03-11 07:00:24 +00005685 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005686 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005687 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005688 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005689
John McCalle5255932011-01-31 22:28:28 +00005690 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005691 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005692 if (RHSPT->getPointeeType()->isVoidType()) {
5693 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005694 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005695 }
John McCall8cb679e2010-11-15 09:13:47 +00005696
Chris Lattnera52c2f22008-01-04 23:18:45 +00005697 return Incompatible;
5698 }
5699
John McCalle5255932011-01-31 22:28:28 +00005700 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005701 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005702 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005703 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005704 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005705 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005706 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikiebbafb8a2012-03-11 07:00:24 +00005707 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005708 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005709 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005710 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005711 return result;
John McCalle5255932011-01-31 22:28:28 +00005712 }
5713
5714 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005715 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005716 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005717 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005718 }
5719
John McCalle5255932011-01-31 22:28:28 +00005720 // In general, C pointers are not compatible with ObjC object pointers,
5721 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005722 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005723 Kind = CK_CPointerToObjCPointerCast;
5724
John McCalle5255932011-01-31 22:28:28 +00005725 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005726 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005727 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005728 }
5729
5730 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005731 if (LHSType->isObjCClassType() &&
5732 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005733 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005734 return Compatible;
5735 }
5736
Steve Naroffaccc4882009-07-20 17:56:53 +00005737 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005738 }
John McCalle5255932011-01-31 22:28:28 +00005739
5740 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005741 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005742 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005743 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005744 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005745 }
5746
Steve Naroff7cae42b2009-07-10 23:34:53 +00005747 return Incompatible;
5748 }
John McCalle5255932011-01-31 22:28:28 +00005749
5750 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005751 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005752 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005753 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005754 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005755 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005756 }
Eli Friedman3360d892008-05-30 18:07:22 +00005757
John McCalle5255932011-01-31 22:28:28 +00005758 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005759 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005760 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005761 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005762 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005763
Chris Lattnera52c2f22008-01-04 23:18:45 +00005764 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005765 }
John McCalle5255932011-01-31 22:28:28 +00005766
5767 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005768 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005769 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005770 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005771 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005772 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005773 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005774
John McCalle5255932011-01-31 22:28:28 +00005775 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005776 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005777 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005778 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005779 }
5780
Steve Naroff7cae42b2009-07-10 23:34:53 +00005781 return Incompatible;
5782 }
Eli Friedman3360d892008-05-30 18:07:22 +00005783
John McCalle5255932011-01-31 22:28:28 +00005784 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005785 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5786 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005787 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005788 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005789 }
Bill Wendling216423b2007-05-30 06:30:29 +00005790 }
John McCalle5255932011-01-31 22:28:28 +00005791
Steve Naroff98cf3e92007-06-06 18:38:38 +00005792 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005793}
5794
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005795/// \brief Constructs a transparent union from an expression that is
5796/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005797static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5798 ExprResult &EResult, QualType UnionType,
5799 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005800 // Build an initializer list that designates the appropriate member
5801 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005802 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005803 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00005804 E, SourceLocation());
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005805 Initializer->setType(UnionType);
5806 Initializer->setInitializedFieldInUnion(Field);
5807
5808 // Build a compound literal constructing a value of the transparent
5809 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005810 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005811 EResult = S.Owned(
5812 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5813 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005814}
5815
5816Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005817Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005818 ExprResult &RHS) {
5819 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005820
Mike Stump11289f42009-09-09 15:08:12 +00005821 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005822 // transparent_union GCC extension.
5823 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005824 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005825 return Incompatible;
5826
5827 // The field to initialize within the transparent union.
5828 RecordDecl *UD = UT->getDecl();
5829 FieldDecl *InitField = 0;
5830 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005831 for (RecordDecl::field_iterator it = UD->field_begin(),
5832 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005833 it != itend; ++it) {
5834 if (it->getType()->isPointerType()) {
5835 // If the transparent union contains a pointer type, we allow:
5836 // 1) void pointer
5837 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005838 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005839 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005840 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie40ed2972012-06-06 20:45:41 +00005841 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005842 break;
5843 }
Mike Stump11289f42009-09-09 15:08:12 +00005844
Richard Trieueb299142011-09-06 20:40:12 +00005845 if (RHS.get()->isNullPointerConstant(Context,
5846 Expr::NPC_ValueDependentIsNull)) {
5847 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5848 CK_NullToPointer);
David Blaikie40ed2972012-06-06 20:45:41 +00005849 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005850 break;
5851 }
5852 }
5853
John McCall8cb679e2010-11-15 09:13:47 +00005854 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005855 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005856 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005857 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie40ed2972012-06-06 20:45:41 +00005858 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005859 break;
5860 }
5861 }
5862
5863 if (!InitField)
5864 return Incompatible;
5865
Richard Trieueb299142011-09-06 20:40:12 +00005866 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005867 return Compatible;
5868}
5869
Chris Lattner9bad62c2008-01-04 18:04:52 +00005870Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005871Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5872 bool Diagnose) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005873 if (getLangOpts().CPlusPlus) {
Eli Friedman0dfb8892011-10-06 23:00:33 +00005874 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005875 // C++ 5.17p3: If the left operand is not of class type, the
5876 // expression is implicitly converted (C++ 4) to the
5877 // cv-unqualified type of the left operand.
Sebastian Redlcc152642011-10-16 18:19:06 +00005878 ExprResult Res;
5879 if (Diagnose) {
5880 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5881 AA_Assigning);
5882 } else {
5883 ImplicitConversionSequence ICS =
5884 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5885 /*SuppressUserConversions=*/false,
5886 /*AllowExplicit=*/false,
5887 /*InOverloadResolution=*/false,
5888 /*CStyle=*/false,
5889 /*AllowObjCWritebackConversion=*/false);
5890 if (ICS.isFailure())
5891 return Incompatible;
5892 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5893 ICS, AA_Assigning);
5894 }
John Wiegley01296292011-04-08 18:41:53 +00005895 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005896 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005897 Sema::AssignConvertType result = Compatible;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005898 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005899 !CheckObjCARCUnavailableWeakConversion(LHSType,
5900 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005901 result = IncompatibleObjCWeakRef;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005902 RHS = Res;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005903 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005904 }
5905
5906 // FIXME: Currently, we fall through and treat C++ classes like C
5907 // structures.
Eli Friedman0dfb8892011-10-06 23:00:33 +00005908 // FIXME: We also fall through for atomics; not sure what should
5909 // happen there, though.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005910 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005911
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005912 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5913 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005914 if ((LHSType->isPointerType() ||
5915 LHSType->isObjCObjectPointerType() ||
5916 LHSType->isBlockPointerType())
5917 && RHS.get()->isNullPointerConstant(Context,
5918 Expr::NPC_ValueDependentIsNull)) {
5919 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005920 return Compatible;
5921 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005922
Chris Lattnere6dcd502007-10-16 02:55:40 +00005923 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005924 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005925 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005926 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005927 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005928 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005929 if (!LHSType->isReferenceType()) {
5930 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5931 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005932 return Incompatible;
5933 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005934
John McCall8cb679e2010-11-15 09:13:47 +00005935 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005936 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00005937 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005938
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005939 // C99 6.5.16.1p2: The value of the right operand is converted to the
5940 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005941 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5942 // so that we can use references in built-in functions even in C.
5943 // The getNonReferenceType() call makes sure that the resulting expression
5944 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00005945 if (result != Incompatible && RHS.get()->getType() != LHSType)
5946 RHS = ImpCastExprToType(RHS.take(),
5947 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005948 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005949}
5950
Richard Trieueb299142011-09-06 20:40:12 +00005951QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5952 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005953 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00005954 << LHS.get()->getType() << RHS.get()->getType()
5955 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005956 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005957}
5958
Richard Trieu859d23f2011-09-06 21:01:04 +00005959QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00005960 SourceLocation Loc, bool IsCompAssign) {
Richard Smith508ebf32011-10-28 03:31:48 +00005961 if (!IsCompAssign) {
5962 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5963 if (LHS.isInvalid())
5964 return QualType();
5965 }
5966 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5967 if (RHS.isInvalid())
5968 return QualType();
5969
Mike Stump4e1f26a2009-02-19 03:04:26 +00005970 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005971 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00005972 QualType LHSType =
5973 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5974 QualType RHSType =
5975 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005976
Nate Begeman191a6b12008-07-14 18:02:46 +00005977 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00005978 if (LHSType == RHSType)
5979 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005980
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005981 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00005982 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5983 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5984 if (LHSType->isExtVectorType()) {
5985 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5986 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005987 }
5988
Richard Trieuba63ce62011-09-09 01:45:06 +00005989 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00005990 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5991 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005992 }
5993
David Blaikiebbafb8a2012-03-11 07:00:24 +00005994 if (getLangOpts().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005995 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005996 // If we are allowing lax vector conversions, and LHS and RHS are both
5997 // vectors, the total size only needs to be the same. This is a
5998 // bitcast; no bits are changed but the result type is different.
5999 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00006000 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6001 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00006002 }
6003
Nate Begemanbd956c42009-06-28 02:36:38 +00006004 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6005 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6006 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00006007 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006008 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00006009 std::swap(RHS, LHS);
6010 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00006011 }
Mike Stump11289f42009-09-09 15:08:12 +00006012
Nate Begeman886448d2009-06-28 19:12:57 +00006013 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00006014 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006015 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00006016 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6017 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00006018 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00006019 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00006020 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00006021 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6022 if (swapped) std::swap(RHS, LHS);
6023 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00006024 }
6025 }
Richard Trieu859d23f2011-09-06 21:01:04 +00006026 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6027 RHSType->isRealFloatingType()) {
6028 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00006029 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00006030 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00006031 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00006032 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6033 if (swapped) std::swap(RHS, LHS);
6034 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00006035 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006036 }
6037 }
Mike Stump11289f42009-09-09 15:08:12 +00006038
Nate Begeman886448d2009-06-28 19:12:57 +00006039 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00006040 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00006041 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00006042 << LHS.get()->getType() << RHS.get()->getType()
6043 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006044 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006045}
6046
Richard Trieuf8916e12011-09-16 00:53:10 +00006047// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6048// expression. These are mainly cases where the null pointer is used as an
6049// integer instead of a pointer.
6050static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6051 SourceLocation Loc, bool IsCompare) {
6052 // The canonical way to check for a GNU null is with isNullPointerConstant,
6053 // but we use a bit of a hack here for speed; this is a relatively
6054 // hot path, and isNullPointerConstant is slow.
6055 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6056 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6057
6058 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6059
6060 // Avoid analyzing cases where the result will either be invalid (and
6061 // diagnosed as such) or entirely valid and not something to warn about.
6062 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6063 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6064 return;
6065
6066 // Comparison operations would not make sense with a null pointer no matter
6067 // what the other expression is.
6068 if (!IsCompare) {
6069 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6070 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6071 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6072 return;
6073 }
6074
6075 // The rest of the operations only make sense with a null pointer
6076 // if the other expression is a pointer.
6077 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6078 NonNullType->canDecayToPointerType())
6079 return;
6080
6081 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6082 << LHSNull /* LHS is NULL */ << NonNullType
6083 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6084}
6085
Richard Trieu859d23f2011-09-06 21:01:04 +00006086QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006087 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006088 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006089 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6090
Richard Trieu859d23f2011-09-06 21:01:04 +00006091 if (LHS.get()->getType()->isVectorType() ||
6092 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006093 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006094
Richard Trieuba63ce62011-09-09 01:45:06 +00006095 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006096 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006097 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006098
David Chisnallfa35df62012-01-16 17:27:18 +00006099
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006100 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu859d23f2011-09-06 21:01:04 +00006101 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006102
Chris Lattnerfaa54172010-01-12 21:23:57 +00006103 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00006104 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00006105 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00006106 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00006107 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6108 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006109
Chris Lattnerfaa54172010-01-12 21:23:57 +00006110 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006111}
6112
Chris Lattnerfaa54172010-01-12 21:23:57 +00006113QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00006114 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006115 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6116
Richard Trieu859d23f2011-09-06 21:01:04 +00006117 if (LHS.get()->getType()->isVectorType() ||
6118 RHS.get()->getType()->isVectorType()) {
6119 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6120 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00006121 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006122 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006123 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006124
Richard Trieuba63ce62011-09-09 01:45:06 +00006125 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006126 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006127 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006128
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006129 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu859d23f2011-09-06 21:01:04 +00006130 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006131
Chris Lattnerfaa54172010-01-12 21:23:57 +00006132 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00006133 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00006134 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00006135 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6136 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006137
Chris Lattnerfaa54172010-01-12 21:23:57 +00006138 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006139}
6140
Chandler Carruthc9332212011-06-27 08:02:19 +00006141/// \brief Diagnose invalid arithmetic on two void pointers.
6142static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006143 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006144 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006145 ? diag::err_typecheck_pointer_arith_void_type
6146 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006147 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6148 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00006149}
6150
6151/// \brief Diagnose invalid arithmetic on a void pointer.
6152static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6153 Expr *Pointer) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006154 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006155 ? diag::err_typecheck_pointer_arith_void_type
6156 : diag::ext_gnu_void_ptr)
6157 << 0 /* one pointer */ << Pointer->getSourceRange();
6158}
6159
6160/// \brief Diagnose invalid arithmetic on two function pointers.
6161static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6162 Expr *LHS, Expr *RHS) {
6163 assert(LHS->getType()->isAnyPointerType());
6164 assert(RHS->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006165 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006166 ? diag::err_typecheck_pointer_arith_function_type
6167 : diag::ext_gnu_ptr_func_arith)
6168 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6169 // We only show the second type if it differs from the first.
6170 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6171 RHS->getType())
6172 << RHS->getType()->getPointeeType()
6173 << LHS->getSourceRange() << RHS->getSourceRange();
6174}
6175
6176/// \brief Diagnose invalid arithmetic on a function pointer.
6177static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6178 Expr *Pointer) {
6179 assert(Pointer->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006180 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006181 ? diag::err_typecheck_pointer_arith_function_type
6182 : diag::ext_gnu_ptr_func_arith)
6183 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6184 << 0 /* one pointer, so only one type */
6185 << Pointer->getSourceRange();
6186}
6187
Richard Trieu993f3ab2011-09-12 18:08:02 +00006188/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00006189///
6190/// \returns True if pointer has incomplete type
6191static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6192 Expr *Operand) {
John McCallf2538342012-07-31 05:14:30 +00006193 assert(Operand->getType()->isAnyPointerType() &&
6194 !Operand->getType()->isDependentType());
6195 QualType PointeeTy = Operand->getType()->getPointeeType();
6196 return S.RequireCompleteType(Loc, PointeeTy,
6197 diag::err_typecheck_arithmetic_incomplete_type,
6198 PointeeTy, Operand->getSourceRange());
Richard Trieuaba22802011-09-02 02:15:37 +00006199}
6200
Chandler Carruthc9332212011-06-27 08:02:19 +00006201/// \brief Check the validity of an arithmetic pointer operand.
6202///
6203/// If the operand has pointer type, this code will check for pointer types
6204/// which are invalid in arithmetic operations. These will be diagnosed
6205/// appropriately, including whether or not the use is supported as an
6206/// extension.
6207///
6208/// \returns True when the operand is valid to use (even if as an extension).
6209static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6210 Expr *Operand) {
6211 if (!Operand->getType()->isAnyPointerType()) return true;
6212
6213 QualType PointeeTy = Operand->getType()->getPointeeType();
6214 if (PointeeTy->isVoidType()) {
6215 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006216 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006217 }
6218 if (PointeeTy->isFunctionType()) {
6219 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006220 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006221 }
6222
Richard Trieuaba22802011-09-02 02:15:37 +00006223 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00006224
6225 return true;
6226}
6227
6228/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6229/// operands.
6230///
6231/// This routine will diagnose any invalid arithmetic on pointer operands much
6232/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6233/// for emitting a single diagnostic even for operations where both LHS and RHS
6234/// are (potentially problematic) pointers.
6235///
6236/// \returns True when the operand is valid to use (even if as an extension).
6237static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006238 Expr *LHSExpr, Expr *RHSExpr) {
6239 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6240 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006241 if (!isLHSPointer && !isRHSPointer) return true;
6242
6243 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00006244 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6245 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006246
6247 // Check for arithmetic on pointers to incomplete types.
6248 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6249 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6250 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006251 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6252 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6253 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006254
David Blaikiebbafb8a2012-03-11 07:00:24 +00006255 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006256 }
6257
6258 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6259 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6260 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006261 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6262 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6263 RHSExpr);
6264 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006265
David Blaikiebbafb8a2012-03-11 07:00:24 +00006266 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006267 }
6268
John McCallf2538342012-07-31 05:14:30 +00006269 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6270 return false;
6271 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6272 return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006273
Chandler Carruthc9332212011-06-27 08:02:19 +00006274 return true;
6275}
6276
Nico Weberccec40d2012-03-02 22:01:22 +00006277/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6278/// literal.
6279static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6280 Expr *LHSExpr, Expr *RHSExpr) {
6281 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6282 Expr* IndexExpr = RHSExpr;
6283 if (!StrExpr) {
6284 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6285 IndexExpr = LHSExpr;
6286 }
6287
6288 bool IsStringPlusInt = StrExpr &&
6289 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6290 if (!IsStringPlusInt)
6291 return;
6292
6293 llvm::APSInt index;
6294 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6295 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6296 if (index.isNonNegative() &&
6297 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6298 index.isUnsigned()))
6299 return;
6300 }
6301
6302 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6303 Self.Diag(OpLoc, diag::warn_string_plus_int)
6304 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6305
6306 // Only print a fixit for "str" + int, not for int + "str".
6307 if (IndexExpr == RHSExpr) {
6308 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6309 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6310 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6311 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6312 << FixItHint::CreateInsertion(EndLoc, "]");
6313 } else
6314 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6315}
6316
Richard Trieu993f3ab2011-09-12 18:08:02 +00006317/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006318static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006319 Expr *LHSExpr, Expr *RHSExpr) {
6320 assert(LHSExpr->getType()->isAnyPointerType());
6321 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006322 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006323 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6324 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006325}
6326
Chris Lattnerfaa54172010-01-12 21:23:57 +00006327QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weberccec40d2012-03-02 22:01:22 +00006328 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6329 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006330 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6331
Richard Trieu4ae7e972011-09-06 21:13:51 +00006332 if (LHS.get()->getType()->isVectorType() ||
6333 RHS.get()->getType()->isVectorType()) {
6334 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006335 if (CompLHSTy) *CompLHSTy = compType;
6336 return compType;
6337 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006338
Richard Trieu4ae7e972011-09-06 21:13:51 +00006339 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6340 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006341 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006342
Nico Weberccec40d2012-03-02 22:01:22 +00006343 // Diagnose "string literal" '+' int.
6344 if (Opc == BO_Add)
6345 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6346
Steve Naroffe4718892007-04-27 18:30:00 +00006347 // handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006348 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006349 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006350 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006351 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006352
John McCallf2538342012-07-31 05:14:30 +00006353 // Type-checking. Ultimately the pointer's going to be in PExp;
6354 // note that we bias towards the LHS being the pointer.
6355 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedman8e122982008-05-18 18:08:51 +00006356
John McCallf2538342012-07-31 05:14:30 +00006357 bool isObjCPointer;
6358 if (PExp->getType()->isPointerType()) {
6359 isObjCPointer = false;
6360 } else if (PExp->getType()->isObjCObjectPointerType()) {
6361 isObjCPointer = true;
6362 } else {
6363 std::swap(PExp, IExp);
6364 if (PExp->getType()->isPointerType()) {
6365 isObjCPointer = false;
6366 } else if (PExp->getType()->isObjCObjectPointerType()) {
6367 isObjCPointer = true;
6368 } else {
6369 return InvalidOperands(Loc, LHS, RHS);
6370 }
6371 }
6372 assert(PExp->getType()->isAnyPointerType());
Chandler Carruthc9332212011-06-27 08:02:19 +00006373
Richard Trieub420bca2011-09-12 18:37:54 +00006374 if (!IExp->getType()->isIntegerType())
6375 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006376
Richard Trieub420bca2011-09-12 18:37:54 +00006377 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6378 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006379
John McCallf2538342012-07-31 05:14:30 +00006380 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieub420bca2011-09-12 18:37:54 +00006381 return QualType();
6382
6383 // Check array bounds for pointer arithemtic
6384 CheckArrayAccess(PExp, IExp);
6385
6386 if (CompLHSTy) {
6387 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6388 if (LHSTy.isNull()) {
6389 LHSTy = LHS.get()->getType();
6390 if (LHSTy->isPromotableIntegerType())
6391 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006392 }
Richard Trieub420bca2011-09-12 18:37:54 +00006393 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006394 }
6395
Richard Trieub420bca2011-09-12 18:37:54 +00006396 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006397}
6398
Chris Lattner2a3569b2008-04-07 05:30:13 +00006399// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006400QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006401 SourceLocation Loc,
6402 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006403 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6404
Richard Trieu4ae7e972011-09-06 21:13:51 +00006405 if (LHS.get()->getType()->isVectorType() ||
6406 RHS.get()->getType()->isVectorType()) {
6407 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006408 if (CompLHSTy) *CompLHSTy = compType;
6409 return compType;
6410 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006411
Richard Trieu4ae7e972011-09-06 21:13:51 +00006412 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6413 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006414 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006415
Chris Lattner4d62f422007-12-09 21:53:25 +00006416 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006417
Chris Lattner4d62f422007-12-09 21:53:25 +00006418 // Handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006419 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006420 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006421 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006422 }
Mike Stump11289f42009-09-09 15:08:12 +00006423
Chris Lattner4d62f422007-12-09 21:53:25 +00006424 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006425 if (LHS.get()->getType()->isAnyPointerType()) {
6426 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006427
Chris Lattner12bdebb2009-04-24 23:50:08 +00006428 // Diagnose bad cases where we step over interface counts.
John McCallf2538342012-07-31 05:14:30 +00006429 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6430 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006431 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006432
Chris Lattner4d62f422007-12-09 21:53:25 +00006433 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006434 if (RHS.get()->getType()->isIntegerType()) {
6435 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006436 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006437
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006438 // Check array bounds for pointer arithemtic
Richard Smith13f67182011-12-16 19:31:14 +00006439 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6440 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006441
Richard Trieu4ae7e972011-09-06 21:13:51 +00006442 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6443 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006444 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006445
Chris Lattner4d62f422007-12-09 21:53:25 +00006446 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006447 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006448 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006449 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006450
David Blaikiebbafb8a2012-03-11 07:00:24 +00006451 if (getLangOpts().CPlusPlus) {
Eli Friedman168fe152009-05-16 13:54:38 +00006452 // Pointee types must be the same: C++ [expr.add]
6453 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006454 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006455 }
6456 } else {
6457 // Pointee types must be compatible C99 6.5.6p3
6458 if (!Context.typesAreCompatible(
6459 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6460 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006461 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006462 return QualType();
6463 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006464 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006465
Chandler Carruthc9332212011-06-27 08:02:19 +00006466 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006467 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006468 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006469
Richard Trieu4ae7e972011-09-06 21:13:51 +00006470 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006471 return Context.getPointerDiffType();
6472 }
6473 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006474
Richard Trieu4ae7e972011-09-06 21:13:51 +00006475 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006476}
6477
Douglas Gregor0bf31402010-10-08 23:50:27 +00006478static bool isScopedEnumerationType(QualType T) {
6479 if (const EnumType *ET = dyn_cast<EnumType>(T))
6480 return ET->getDecl()->isScoped();
6481 return false;
6482}
6483
Richard Trieue4a19fb2011-09-06 21:21:28 +00006484static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006485 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006486 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006487 llvm::APSInt Right;
6488 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006489 if (RHS.get()->isValueDependent() ||
6490 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006491 return;
6492
6493 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006494 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006495 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006496 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006497 return;
6498 }
6499 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006500 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006501 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006502 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006503 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006504 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006505 return;
6506 }
6507 if (Opc != BO_Shl)
6508 return;
6509
6510 // When left shifting an ICE which is signed, we can check for overflow which
6511 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6512 // integers have defined behavior modulo one more than the maximum value
6513 // representable in the result type, so never warn for those.
6514 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006515 if (LHS.get()->isValueDependent() ||
6516 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6517 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006518 return;
6519 llvm::APInt ResultBits =
6520 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6521 if (LeftBits.uge(ResultBits))
6522 return;
6523 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6524 Result = Result.shl(Right);
6525
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006526 // Print the bit representation of the signed integer as an unsigned
6527 // hexadecimal number.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006528 SmallString<40> HexResult;
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006529 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6530
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006531 // If we are only missing a sign bit, this is less likely to result in actual
6532 // bugs -- if the result is cast back to an unsigned type, it will have the
6533 // expected value. Thus we place this behind a different warning that can be
6534 // turned off separately if needed.
6535 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006536 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006537 << HexResult.str() << LHSType
6538 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006539 return;
6540 }
6541
6542 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006543 << HexResult.str() << Result.getMinSignedBits() << LHSType
6544 << Left.getBitWidth() << LHS.get()->getSourceRange()
6545 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006546}
6547
Chris Lattner2a3569b2008-04-07 05:30:13 +00006548// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006549QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006550 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006551 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006552 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6553
Chris Lattner5c11c412007-12-12 05:47:28 +00006554 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006555 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6556 !RHS.get()->getType()->hasIntegerRepresentation())
6557 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006558
Douglas Gregor0bf31402010-10-08 23:50:27 +00006559 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6560 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006561 if (isScopedEnumerationType(LHS.get()->getType()) ||
6562 isScopedEnumerationType(RHS.get()->getType())) {
6563 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006564 }
6565
Nate Begemane46ee9a2009-10-25 02:26:48 +00006566 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006567 if (LHS.get()->getType()->isVectorType() ||
6568 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006569 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006570
Chris Lattner5c11c412007-12-12 05:47:28 +00006571 // Shifts don't perform usual arithmetic conversions, they just do integer
6572 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006573
John McCall57cdd882010-12-16 19:28:59 +00006574 // For the LHS, do usual unary conversions, but then reset them away
6575 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006576 ExprResult OldLHS = LHS;
6577 LHS = UsualUnaryConversions(LHS.take());
6578 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006579 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006580 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006581 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006582
6583 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006584 RHS = UsualUnaryConversions(RHS.take());
6585 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006586 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006587
Ryan Flynnf53fab82009-08-07 16:20:20 +00006588 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006589 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006590
Chris Lattner5c11c412007-12-12 05:47:28 +00006591 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006592 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006593}
6594
Chandler Carruth17773fc2010-07-10 12:30:03 +00006595static bool IsWithinTemplateSpecialization(Decl *D) {
6596 if (DeclContext *DC = D->getDeclContext()) {
6597 if (isa<ClassTemplateSpecializationDecl>(DC))
6598 return true;
6599 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6600 return FD->isFunctionTemplateSpecialization();
6601 }
6602 return false;
6603}
6604
Richard Trieueea56f72011-09-02 03:48:46 +00006605/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006606static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6607 ExprResult &RHS) {
6608 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6609 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006610
6611 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6612 if (!LHSEnumType)
6613 return;
6614 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6615 if (!RHSEnumType)
6616 return;
6617
6618 // Ignore anonymous enums.
6619 if (!LHSEnumType->getDecl()->getIdentifier())
6620 return;
6621 if (!RHSEnumType->getDecl()->getIdentifier())
6622 return;
6623
6624 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6625 return;
6626
6627 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6628 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006629 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006630}
6631
Richard Trieudd82a5c2011-09-02 02:55:45 +00006632/// \brief Diagnose bad pointer comparisons.
6633static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006634 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006635 bool IsError) {
6636 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006637 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006638 << LHS.get()->getType() << RHS.get()->getType()
6639 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006640}
6641
6642/// \brief Returns false if the pointers are converted to a composite type,
6643/// true otherwise.
6644static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006645 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006646 // C++ [expr.rel]p2:
6647 // [...] Pointer conversions (4.10) and qualification
6648 // conversions (4.4) are performed on pointer operands (or on
6649 // a pointer operand and a null pointer constant) to bring
6650 // them to their composite pointer type. [...]
6651 //
6652 // C++ [expr.eq]p1 uses the same notion for (in)equality
6653 // comparisons of pointers.
6654
6655 // C++ [expr.eq]p2:
6656 // In addition, pointers to members can be compared, or a pointer to
6657 // member and a null pointer constant. Pointer to member conversions
6658 // (4.11) and qualification conversions (4.4) are performed to bring
6659 // them to a common type. If one operand is a null pointer constant,
6660 // the common type is the type of the other operand. Otherwise, the
6661 // common type is a pointer to member type similar (4.4) to the type
6662 // of one of the operands, with a cv-qualification signature (4.4)
6663 // that is the union of the cv-qualification signatures of the operand
6664 // types.
6665
Richard Trieu1762d7c2011-09-06 21:27:33 +00006666 QualType LHSType = LHS.get()->getType();
6667 QualType RHSType = RHS.get()->getType();
6668 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6669 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006670
6671 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006672 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006673 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006674 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006675 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006676 return true;
6677 }
6678
6679 if (NonStandardCompositeType)
6680 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006681 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6682 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006683
Richard Trieu1762d7c2011-09-06 21:27:33 +00006684 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6685 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006686 return false;
6687}
6688
6689static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006690 ExprResult &LHS,
6691 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006692 bool IsError) {
6693 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6694 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006695 << LHS.get()->getType() << RHS.get()->getType()
6696 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006697}
6698
Jordan Rosed49a33e2012-06-08 21:14:25 +00006699static bool isObjCObjectLiteral(ExprResult &E) {
6700 switch (E.get()->getStmtClass()) {
6701 case Stmt::ObjCArrayLiteralClass:
6702 case Stmt::ObjCDictionaryLiteralClass:
6703 case Stmt::ObjCStringLiteralClass:
6704 case Stmt::ObjCBoxedExprClass:
6705 return true;
6706 default:
6707 // Note that ObjCBoolLiteral is NOT an object literal!
6708 return false;
6709 }
6710}
6711
Jordan Rose7660f782012-07-17 17:46:40 +00006712static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6713 // Get the LHS object's interface type.
6714 QualType Type = LHS->getType();
6715 QualType InterfaceType;
6716 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6717 InterfaceType = PTy->getPointeeType();
6718 if (const ObjCObjectType *iQFaceTy =
6719 InterfaceType->getAsObjCQualifiedInterfaceType())
6720 InterfaceType = iQFaceTy->getBaseType();
6721 } else {
6722 // If this is not actually an Objective-C object, bail out.
6723 return false;
6724 }
6725
6726 // If the RHS isn't an Objective-C object, bail out.
6727 if (!RHS->getType()->isObjCObjectPointerType())
6728 return false;
6729
6730 // Try to find the -isEqual: method.
6731 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6732 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6733 InterfaceType,
6734 /*instance=*/true);
6735 if (!Method) {
6736 if (Type->isObjCIdType()) {
6737 // For 'id', just check the global pool.
6738 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6739 /*receiverId=*/true,
6740 /*warn=*/false);
6741 } else {
6742 // Check protocols.
6743 Method = S.LookupMethodInQualifiedType(IsEqualSel,
6744 cast<ObjCObjectPointerType>(Type),
6745 /*instance=*/true);
6746 }
6747 }
6748
6749 if (!Method)
6750 return false;
6751
6752 QualType T = Method->param_begin()[0]->getType();
6753 if (!T->isObjCObjectPointerType())
6754 return false;
6755
6756 QualType R = Method->getResultType();
6757 if (!R->isScalarType())
6758 return false;
6759
6760 return true;
6761}
6762
6763static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6764 ExprResult &LHS, ExprResult &RHS,
6765 BinaryOperator::Opcode Opc){
Jordan Rose63ffaa82012-07-17 17:46:48 +00006766 Expr *Literal;
6767 Expr *Other;
6768 if (isObjCObjectLiteral(LHS)) {
6769 Literal = LHS.get();
6770 Other = RHS.get();
6771 } else {
6772 Literal = RHS.get();
6773 Other = LHS.get();
6774 }
6775
6776 // Don't warn on comparisons against nil.
6777 Other = Other->IgnoreParenCasts();
6778 if (Other->isNullPointerConstant(S.getASTContext(),
6779 Expr::NPC_ValueDependentIsNotNull))
6780 return;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006781
Jordan Roseea70bf72012-07-17 17:46:44 +00006782 // This should be kept in sync with warn_objc_literal_comparison.
Jordan Rose63ffaa82012-07-17 17:46:48 +00006783 // LK_String should always be last, since it has its own warning flag.
Jordan Roseea70bf72012-07-17 17:46:44 +00006784 enum {
6785 LK_Array,
6786 LK_Dictionary,
6787 LK_Numeric,
6788 LK_Boxed,
6789 LK_String
6790 } LiteralKind;
6791
Jordan Rosed49a33e2012-06-08 21:14:25 +00006792 switch (Literal->getStmtClass()) {
6793 case Stmt::ObjCStringLiteralClass:
6794 // "string literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006795 LiteralKind = LK_String;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006796 break;
6797 case Stmt::ObjCArrayLiteralClass:
6798 // "array literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006799 LiteralKind = LK_Array;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006800 break;
6801 case Stmt::ObjCDictionaryLiteralClass:
6802 // "dictionary literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006803 LiteralKind = LK_Dictionary;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006804 break;
6805 case Stmt::ObjCBoxedExprClass: {
6806 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6807 switch (Inner->getStmtClass()) {
6808 case Stmt::IntegerLiteralClass:
6809 case Stmt::FloatingLiteralClass:
6810 case Stmt::CharacterLiteralClass:
6811 case Stmt::ObjCBoolLiteralExprClass:
6812 case Stmt::CXXBoolLiteralExprClass:
6813 // "numeric literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006814 LiteralKind = LK_Numeric;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006815 break;
6816 case Stmt::ImplicitCastExprClass: {
6817 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6818 // Boolean literals can be represented by implicit casts.
6819 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
Jordan Roseea70bf72012-07-17 17:46:44 +00006820 LiteralKind = LK_Numeric;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006821 break;
6822 }
6823 // FALLTHROUGH
6824 }
6825 default:
6826 // "boxed expression"
Jordan Roseea70bf72012-07-17 17:46:44 +00006827 LiteralKind = LK_Boxed;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006828 break;
6829 }
6830 break;
6831 }
6832 default:
6833 llvm_unreachable("Unknown Objective-C object literal kind");
6834 }
6835
Jordan Roseea70bf72012-07-17 17:46:44 +00006836 if (LiteralKind == LK_String)
6837 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6838 << Literal->getSourceRange();
6839 else
6840 S.Diag(Loc, diag::warn_objc_literal_comparison)
6841 << LiteralKind << Literal->getSourceRange();
Jordan Rosed49a33e2012-06-08 21:14:25 +00006842
Jordan Rose7660f782012-07-17 17:46:40 +00006843 if (BinaryOperator::isEqualityOp(Opc) &&
6844 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6845 SourceLocation Start = LHS.get()->getLocStart();
6846 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6847 SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rosef9198032012-07-09 16:54:44 +00006848
Jordan Rose7660f782012-07-17 17:46:40 +00006849 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6850 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6851 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6852 << FixItHint::CreateInsertion(End, "]");
Jordan Rosed49a33e2012-06-08 21:14:25 +00006853 }
Jordan Rosed49a33e2012-06-08 21:14:25 +00006854}
6855
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006856// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006857QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006858 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006859 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006860 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6861
John McCalle3027922010-08-25 11:45:40 +00006862 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006863
Chris Lattner9a152e22009-12-05 05:40:13 +00006864 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006865 if (LHS.get()->getType()->isVectorType() ||
6866 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006867 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006868
Richard Trieub80728f2011-09-06 21:43:51 +00006869 QualType LHSType = LHS.get()->getType();
6870 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006871
Richard Trieub80728f2011-09-06 21:43:51 +00006872 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6873 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006874
Richard Trieub80728f2011-09-06 21:43:51 +00006875 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006876
Richard Trieub80728f2011-09-06 21:43:51 +00006877 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006878 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006879 !LHS.get()->getLocStart().isMacroID() &&
6880 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006881 // For non-floating point types, check for self-comparisons of the form
6882 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6883 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006884 //
6885 // NOTE: Don't warn about comparison expressions resulting from macro
6886 // expansion. Also don't warn about comparisons which are only self
6887 // comparisons within a template specialization. The warnings should catch
6888 // obvious cases in the definition of the template anyways. The idea is to
6889 // warn when the typed comparison operator will always evaluate to the same
6890 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006891 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006892 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006893 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006894 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006895 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006896 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006897 << (Opc == BO_EQ
6898 || Opc == BO_LE
6899 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006900 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006901 !DRL->getDecl()->getType()->isReferenceType() &&
6902 !DRR->getDecl()->getType()->isReferenceType()) {
6903 // what is it always going to eval to?
6904 char always_evals_to;
6905 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006906 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006907 always_evals_to = 0; // false
6908 break;
John McCalle3027922010-08-25 11:45:40 +00006909 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006910 always_evals_to = 1; // true
6911 break;
6912 default:
6913 // best we can say is 'a constant'
6914 always_evals_to = 2; // e.g. array1 <= array2
6915 break;
6916 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006917 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006918 << 1 // array
6919 << always_evals_to);
6920 }
6921 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006922 }
Mike Stump11289f42009-09-09 15:08:12 +00006923
Chris Lattner222b8bd2009-03-08 19:39:53 +00006924 if (isa<CastExpr>(LHSStripped))
6925 LHSStripped = LHSStripped->IgnoreParenCasts();
6926 if (isa<CastExpr>(RHSStripped))
6927 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006928
Chris Lattner222b8bd2009-03-08 19:39:53 +00006929 // Warn about comparisons against a string constant (unless the other
6930 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006931 Expr *literalString = 0;
6932 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006933 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006934 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006935 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006936 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006937 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006938 } else if ((isa<StringLiteral>(RHSStripped) ||
6939 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006940 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006941 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006942 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006943 literalStringStripped = RHSStripped;
6944 }
6945
6946 if (literalString) {
6947 std::string resultComparison;
6948 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006949 case BO_LT: resultComparison = ") < 0"; break;
6950 case BO_GT: resultComparison = ") > 0"; break;
6951 case BO_LE: resultComparison = ") <= 0"; break;
6952 case BO_GE: resultComparison = ") >= 0"; break;
6953 case BO_EQ: resultComparison = ") == 0"; break;
6954 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00006955 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006956 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006957
Ted Kremenek3427fac2011-02-23 01:52:04 +00006958 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006959 PDiag(diag::warn_stringcompare)
6960 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006961 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006962 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006963 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006964
Douglas Gregorec170db2010-06-08 19:50:34 +00006965 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00006966 if (LHS.get()->getType()->isArithmeticType() &&
6967 RHS.get()->getType()->isArithmeticType()) {
6968 UsualArithmeticConversions(LHS, RHS);
6969 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006970 return QualType();
6971 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006972 else {
Richard Trieub80728f2011-09-06 21:43:51 +00006973 LHS = UsualUnaryConversions(LHS.take());
6974 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006975 return QualType();
6976
Richard Trieub80728f2011-09-06 21:43:51 +00006977 RHS = UsualUnaryConversions(RHS.take());
6978 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006979 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006980 }
6981
Richard Trieub80728f2011-09-06 21:43:51 +00006982 LHSType = LHS.get()->getType();
6983 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006984
Douglas Gregorca63811b2008-11-19 03:25:36 +00006985 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006986 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006987
Richard Trieuba63ce62011-09-09 01:45:06 +00006988 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00006989 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006990 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006991 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006992 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00006993 if (LHSType->hasFloatingRepresentation())
6994 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006995
Richard Trieub80728f2011-09-06 21:43:51 +00006996 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006997 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006998 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006999
Richard Trieub80728f2011-09-06 21:43:51 +00007000 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007001 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00007002 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007003 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007004
Douglas Gregorf267edd2010-06-15 21:38:40 +00007005 // All of the following pointer-related warnings are GCC extensions, except
7006 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00007007 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00007008 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00007009 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00007010 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00007011 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007012
David Blaikiebbafb8a2012-03-11 07:00:24 +00007013 if (getLangOpts().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00007014 if (LCanPointeeTy == RCanPointeeTy)
7015 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00007016 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007017 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7018 // Valid unless comparison between non-null pointer and function pointer
7019 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00007020 // In a SFINAE context, we treat this as a hard error to maintain
7021 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007022 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7023 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00007024 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00007025 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00007026
7027 if (isSFINAEContext())
7028 return QualType();
7029
Richard Trieub80728f2011-09-06 21:43:51 +00007030 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007031 return ResultTy;
7032 }
7033 }
Anders Carlssona95069c2010-11-04 03:17:43 +00007034
Richard Trieub80728f2011-09-06 21:43:51 +00007035 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007036 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00007037 else
7038 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007039 }
Eli Friedman16c209612009-08-23 00:27:47 +00007040 // C99 6.5.9p2 and C99 6.5.8p2
7041 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7042 RCanPointeeTy.getUnqualifiedType())) {
7043 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00007044 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00007045 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00007046 << LHSType << RHSType << LHS.get()->getSourceRange()
7047 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007048 }
Richard Trieuba63ce62011-09-09 01:45:06 +00007049 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00007050 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7051 // Valid unless comparison between non-null pointer and function pointer
7052 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00007053 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007054 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007055 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00007056 } else {
7057 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00007058 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00007059 }
John McCall7684dde2011-03-11 04:25:25 +00007060 if (LCanPointeeTy != RCanPointeeTy) {
7061 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007062 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007063 else
Richard Trieub80728f2011-09-06 21:43:51 +00007064 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007065 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007066 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007067 }
Mike Stump11289f42009-09-09 15:08:12 +00007068
David Blaikiebbafb8a2012-03-11 07:00:24 +00007069 if (getLangOpts().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007070 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00007071 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00007072 return ResultTy;
7073
Mike Stump11289f42009-09-09 15:08:12 +00007074 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007075 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007076 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00007077 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00007078 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007079 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7080 RHS = ImpCastExprToType(RHS.take(), LHSType,
7081 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007082 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007083 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007084 return ResultTy;
7085 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007086 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00007087 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00007088 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007089 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7090 LHS = ImpCastExprToType(LHS.take(), RHSType,
7091 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007092 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007093 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007094 return ResultTy;
7095 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007096
7097 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00007098 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007099 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7100 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007101 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00007102 else
7103 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007104 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007105
7106 // Handle scoped enumeration types specifically, since they don't promote
7107 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00007108 if (LHS.get()->getType()->isEnumeralType() &&
7109 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7110 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007111 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007112 }
Mike Stump11289f42009-09-09 15:08:12 +00007113
Steve Naroff081c7422008-09-04 15:10:53 +00007114 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00007115 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00007116 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00007117 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7118 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007119
Steve Naroff081c7422008-09-04 15:10:53 +00007120 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007121 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007122 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007123 << LHSType << RHSType << LHS.get()->getSourceRange()
7124 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007125 }
Richard Trieub80728f2011-09-06 21:43:51 +00007126 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007127 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007128 }
John Wiegley01296292011-04-08 18:41:53 +00007129
Steve Naroffe18f94c2008-09-28 01:11:11 +00007130 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00007131 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00007132 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7133 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007134 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00007135 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007136 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00007137 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007138 ->getPointeeType()->isVoidType())))
7139 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007140 << LHSType << RHSType << LHS.get()->getSourceRange()
7141 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007142 }
John McCall7684dde2011-03-11 04:25:25 +00007143 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00007144 LHS = ImpCastExprToType(LHS.take(), RHSType,
7145 RHSType->isPointerType() ? CK_BitCast
7146 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00007147 else
John McCall9320b872011-09-09 05:25:32 +00007148 RHS = ImpCastExprToType(RHS.take(), LHSType,
7149 LHSType->isPointerType() ? CK_BitCast
7150 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007151 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007152 }
Steve Naroff081c7422008-09-04 15:10:53 +00007153
Richard Trieub80728f2011-09-06 21:43:51 +00007154 if (LHSType->isObjCObjectPointerType() ||
7155 RHSType->isObjCObjectPointerType()) {
7156 const PointerType *LPT = LHSType->getAs<PointerType>();
7157 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00007158 if (LPT || RPT) {
7159 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7160 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007161
Steve Naroff753567f2008-11-17 19:49:16 +00007162 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00007163 !Context.typesAreCompatible(LHSType, RHSType)) {
7164 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007165 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007166 }
John McCall7684dde2011-03-11 04:25:25 +00007167 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00007168 LHS = ImpCastExprToType(LHS.take(), RHSType,
7169 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00007170 else
John McCall9320b872011-09-09 05:25:32 +00007171 RHS = ImpCastExprToType(RHS.take(), LHSType,
7172 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007173 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007174 }
Richard Trieub80728f2011-09-06 21:43:51 +00007175 if (LHSType->isObjCObjectPointerType() &&
7176 RHSType->isObjCObjectPointerType()) {
7177 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7178 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007179 /*isError*/false);
Jordan Rosed49a33e2012-06-08 21:14:25 +00007180 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose7660f782012-07-17 17:46:40 +00007181 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rosed49a33e2012-06-08 21:14:25 +00007182
John McCall7684dde2011-03-11 04:25:25 +00007183 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007184 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007185 else
Richard Trieub80728f2011-09-06 21:43:51 +00007186 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007187 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007188 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007189 }
Richard Trieub80728f2011-09-06 21:43:51 +00007190 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7191 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007192 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007193 bool isError = false;
Richard Trieub80728f2011-09-06 21:43:51 +00007194 if ((LHSIsNull && LHSType->isIntegerType()) ||
7195 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007196 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007197 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007198 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007199 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007200 else if (getLangOpts().CPlusPlus) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007201 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7202 isError = true;
7203 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007204 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007205
Chris Lattnerd99bd522009-08-23 00:03:44 +00007206 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007207 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00007208 << LHSType << RHSType << LHS.get()->getSourceRange()
7209 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007210 if (isError)
7211 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007212 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007213
Richard Trieub80728f2011-09-06 21:43:51 +00007214 if (LHSType->isIntegerType())
7215 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007216 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007217 else
Richard Trieub80728f2011-09-06 21:43:51 +00007218 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007219 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007220 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007221 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007222
Steve Naroff4b191572008-09-04 16:56:14 +00007223 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00007224 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007225 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7226 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007227 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007228 }
Richard Trieuba63ce62011-09-09 01:45:06 +00007229 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007230 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7231 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007232 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007233 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007234
Richard Trieub80728f2011-09-06 21:43:51 +00007235 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007236}
7237
Tanya Lattner20248222012-01-16 21:02:28 +00007238
7239// Return a signed type that is of identical size and number of elements.
7240// For floating point vectors, return an integer type of identical size
7241// and number of elements.
7242QualType Sema::GetSignedVectorType(QualType V) {
7243 const VectorType *VTy = V->getAs<VectorType>();
7244 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7245 if (TypeSize == Context.getTypeSize(Context.CharTy))
7246 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7247 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7248 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7249 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7250 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7251 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7252 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7253 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7254 "Unhandled vector element size in vector compare");
7255 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7256}
7257
Nate Begeman191a6b12008-07-14 18:02:46 +00007258/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007259/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007260/// like a scalar comparison, a vector comparison produces a vector of integer
7261/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00007262QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007263 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007264 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00007265 // Check to make sure we're operating on vectors of the same type and width,
7266 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00007267 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00007268 if (vType.isNull())
7269 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007270
Richard Trieubcce2f72011-09-07 01:19:57 +00007271 QualType LHSType = LHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007272
Anton Yartsev530deb92011-03-27 15:36:07 +00007273 // If AltiVec, the comparison results in a numeric type, i.e.
7274 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007275 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007276 return Context.getLogicalOperationType();
7277
Nate Begeman191a6b12008-07-14 18:02:46 +00007278 // For non-floating point types, check for self-comparisons of the form
7279 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7280 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00007281 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith508ebf32011-10-28 03:31:48 +00007282 if (DeclRefExpr* DRL
7283 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7284 if (DeclRefExpr* DRR
7285 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007286 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007287 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007288 PDiag(diag::warn_comparison_always)
7289 << 0 // self-
7290 << 2 // "a constant"
7291 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007292 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007293
Nate Begeman191a6b12008-07-14 18:02:46 +00007294 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00007295 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikieca043222012-01-16 05:16:03 +00007296 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieubcce2f72011-09-07 01:19:57 +00007297 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007298 }
Tanya Lattner20248222012-01-16 21:02:28 +00007299
7300 // Return a signed type for the vector.
7301 return GetSignedVectorType(LHSType);
7302}
Mike Stump4e1f26a2009-02-19 03:04:26 +00007303
Tanya Lattner3dd33b22012-01-19 01:16:16 +00007304QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7305 SourceLocation Loc) {
Tanya Lattner20248222012-01-16 21:02:28 +00007306 // Ensure that either both operands are of the same vector type, or
7307 // one operand is of a vector type and the other is of its element type.
7308 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7309 if (vType.isNull() || vType->isFloatingType())
7310 return InvalidOperands(Loc, LHS, RHS);
7311
7312 return GetSignedVectorType(LHS.get()->getType());
Nate Begeman191a6b12008-07-14 18:02:46 +00007313}
7314
Steve Naroff218bc2b2007-05-04 21:54:46 +00007315inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00007316 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00007317 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7318
Richard Trieubcce2f72011-09-07 01:19:57 +00007319 if (LHS.get()->getType()->isVectorType() ||
7320 RHS.get()->getType()->isVectorType()) {
7321 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7322 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00007323 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007324
Richard Trieubcce2f72011-09-07 01:19:57 +00007325 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007326 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007327
Richard Trieubcce2f72011-09-07 01:19:57 +00007328 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7329 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00007330 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00007331 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007332 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00007333 LHS = LHSResult.take();
7334 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007335
Eli Friedman93ee5ca2012-06-16 02:19:17 +00007336 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007337 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00007338 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007339}
7340
Steve Naroff218bc2b2007-05-04 21:54:46 +00007341inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00007342 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00007343
Tanya Lattner20248222012-01-16 21:02:28 +00007344 // Check vector operands differently.
7345 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7346 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7347
Chris Lattner8406c512010-07-13 19:41:32 +00007348 // Diagnose cases where the user write a logical and/or but probably meant a
7349 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7350 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00007351 if (LHS.get()->getType()->isIntegerType() &&
7352 !LHS.get()->getType()->isBooleanType() &&
7353 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00007354 // Don't warn in macros or template instantiations.
7355 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00007356 // If the RHS can be constant folded, and if it constant folds to something
7357 // that isn't 0 or 1 (which indicate a potential logical operation that
7358 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007359 // Parens on the RHS are ignored.
Richard Smith00ab3ae2011-10-16 23:01:09 +00007360 llvm::APSInt Result;
7361 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikiebbafb8a2012-03-11 07:00:24 +00007362 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith00ab3ae2011-10-16 23:01:09 +00007363 (Result != 0 && Result != 1)) {
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007364 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00007365 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007366 << (Opc == BO_LAnd ? "&&" : "||");
7367 // Suggest replacing the logical operator with the bitwise version
7368 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7369 << (Opc == BO_LAnd ? "&" : "|")
7370 << FixItHint::CreateReplacement(SourceRange(
7371 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007372 getLangOpts())),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007373 Opc == BO_LAnd ? "&" : "|");
7374 if (Opc == BO_LAnd)
7375 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7376 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7377 << FixItHint::CreateRemoval(
7378 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00007379 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007380 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007381 getLangOpts()),
Richard Trieubcce2f72011-09-07 01:19:57 +00007382 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007383 }
Chris Lattner938533d2010-07-24 01:10:11 +00007384 }
Chris Lattner8406c512010-07-13 19:41:32 +00007385
David Blaikiebbafb8a2012-03-11 07:00:24 +00007386 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00007387 LHS = UsualUnaryConversions(LHS.take());
7388 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007389 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007390
Richard Trieubcce2f72011-09-07 01:19:57 +00007391 RHS = UsualUnaryConversions(RHS.take());
7392 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007393 return QualType();
7394
Richard Trieubcce2f72011-09-07 01:19:57 +00007395 if (!LHS.get()->getType()->isScalarType() ||
7396 !RHS.get()->getType()->isScalarType())
7397 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007398
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007399 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007400 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007401
John McCall4a2429a2010-06-04 00:29:51 +00007402 // The following is safe because we only use this method for
7403 // non-overloadable operands.
7404
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007405 // C++ [expr.log.and]p1
7406 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007407 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00007408 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7409 if (LHSRes.isInvalid())
7410 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007411 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00007412
Richard Trieubcce2f72011-09-07 01:19:57 +00007413 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7414 if (RHSRes.isInvalid())
7415 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007416 RHS = RHSRes;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007417
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007418 // C++ [expr.log.and]p2
7419 // C++ [expr.log.or]p2
7420 // The result is a bool.
7421 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007422}
7423
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007424/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7425/// is a read-only property; return true if so. A readonly property expression
7426/// depends on various declarations and thus must be treated specially.
7427///
Mike Stump11289f42009-09-09 15:08:12 +00007428static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007429 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7430 if (!PropExpr) return false;
7431 if (PropExpr->isImplicitProperty()) return false;
John McCallb7bd14f2010-12-02 01:19:52 +00007432
John McCall526ab472011-10-25 17:37:35 +00007433 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7434 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCallb7bd14f2010-12-02 01:19:52 +00007435 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007436 PropExpr->getBase()->getType();
7437
John McCall526ab472011-10-25 17:37:35 +00007438 if (const ObjCObjectPointerType *OPT =
7439 BaseType->getAsObjCInterfacePointerType())
7440 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7441 if (S.isPropertyReadonly(PDecl, IFace))
7442 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007443 return false;
7444}
7445
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007446static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007447 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7448 if (!ME) return false;
7449 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7450 ObjCMessageExpr *Base =
7451 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7452 if (!Base) return false;
7453 return Base->getMethodDecl() != 0;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007454}
7455
John McCall5fa2ef42012-03-13 00:37:01 +00007456/// Is the given expression (which must be 'const') a reference to a
7457/// variable which was originally non-const, but which has become
7458/// 'const' due to being captured within a block?
7459enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7460static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7461 assert(E->isLValue() && E->getType().isConstQualified());
7462 E = E->IgnoreParens();
7463
7464 // Must be a reference to a declaration from an enclosing scope.
7465 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7466 if (!DRE) return NCCK_None;
7467 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7468
7469 // The declaration must be a variable which is not declared 'const'.
7470 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7471 if (!var) return NCCK_None;
7472 if (var->getType().isConstQualified()) return NCCK_None;
7473 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7474
7475 // Decide whether the first capture was for a block or a lambda.
7476 DeclContext *DC = S.CurContext;
7477 while (DC->getParent() != var->getDeclContext())
7478 DC = DC->getParent();
7479 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7480}
7481
Chris Lattner30bd3272008-11-18 01:22:49 +00007482/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7483/// emit an error and return true. If so, return false.
7484static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianca5c5972012-04-10 17:30:10 +00007485 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007486 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007487 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007488 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007489 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7490 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007491 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7492 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007493 if (IsLV == Expr::MLV_Valid)
7494 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007495
Chris Lattner30bd3272008-11-18 01:22:49 +00007496 unsigned Diag = 0;
7497 bool NeedType = false;
7498 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007499 case Expr::MLV_ConstQualified:
7500 Diag = diag::err_typecheck_assign_const;
7501
John McCall5fa2ef42012-03-13 00:37:01 +00007502 // Use a specialized diagnostic when we're assigning to an object
7503 // from an enclosing function or block.
7504 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7505 if (NCCK == NCCK_Block)
7506 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7507 else
7508 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7509 break;
7510 }
7511
John McCalld4631322011-06-17 06:42:21 +00007512 // In ARC, use some specialized diagnostics for occasions where we
7513 // infer 'const'. These are always pseudo-strong variables.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007514 if (S.getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00007515 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7516 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7517 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7518
John McCalld4631322011-06-17 06:42:21 +00007519 // Use the normal diagnostic if it's pseudo-__strong but the
7520 // user actually wrote 'const'.
7521 if (var->isARCPseudoStrong() &&
7522 (!var->getTypeSourceInfo() ||
7523 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7524 // There are two pseudo-strong cases:
7525 // - self
John McCall31168b02011-06-15 23:02:42 +00007526 ObjCMethodDecl *method = S.getCurMethodDecl();
7527 if (method && var == method->getSelfDecl())
Ted Kremenek1fcdaa92011-11-14 21:59:25 +00007528 Diag = method->isClassMethod()
7529 ? diag::err_typecheck_arc_assign_self_class_method
7530 : diag::err_typecheck_arc_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007531
7532 // - fast enumeration variables
7533 else
John McCall31168b02011-06-15 23:02:42 +00007534 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007535
John McCall31168b02011-06-15 23:02:42 +00007536 SourceRange Assign;
7537 if (Loc != OrigLoc)
7538 Assign = SourceRange(OrigLoc, OrigLoc);
7539 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7540 // We need to preserve the AST regardless, so migration tool
7541 // can do its job.
7542 return false;
7543 }
7544 }
7545 }
7546
7547 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007548 case Expr::MLV_ArrayType:
Richard Smitheb3cad52012-06-04 22:27:30 +00007549 case Expr::MLV_ArrayTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007550 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7551 NeedType = true;
7552 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007553 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007554 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7555 NeedType = true;
7556 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007557 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007558 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7559 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007560 case Expr::MLV_Valid:
7561 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007562 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007563 case Expr::MLV_MemberFunction:
7564 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007565 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7566 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007567 case Expr::MLV_IncompleteType:
7568 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007569 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007570 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner9bad62c2008-01-04 18:04:52 +00007571 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007572 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7573 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007574 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007575 case Expr::MLV_NoSetterProperty:
John McCall526ab472011-10-25 17:37:35 +00007576 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007577 case Expr::MLV_InvalidMessageExpression:
7578 Diag = diag::error_readonly_message_assignment;
7579 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007580 case Expr::MLV_SubObjCPropertySetting:
7581 Diag = diag::error_no_subobject_property_setting;
7582 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007583 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007584
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007585 SourceRange Assign;
7586 if (Loc != OrigLoc)
7587 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007588 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007589 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007590 else
Mike Stump11289f42009-09-09 15:08:12 +00007591 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007592 return true;
7593}
7594
Nico Weberb8124d12012-07-03 02:03:06 +00007595static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7596 SourceLocation Loc,
7597 Sema &Sema) {
7598 // C / C++ fields
Nico Weber33fd5232012-06-28 23:53:12 +00007599 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7600 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7601 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7602 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weberb8124d12012-07-03 02:03:06 +00007603 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber33fd5232012-06-28 23:53:12 +00007604 }
Chris Lattner30bd3272008-11-18 01:22:49 +00007605
Nico Weberb8124d12012-07-03 02:03:06 +00007606 // Objective-C instance variables
Nico Weber33fd5232012-06-28 23:53:12 +00007607 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7608 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7609 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7610 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7611 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7612 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weberb8124d12012-07-03 02:03:06 +00007613 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber33fd5232012-06-28 23:53:12 +00007614 }
7615}
Chris Lattner30bd3272008-11-18 01:22:49 +00007616
7617// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007618QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007619 SourceLocation Loc,
7620 QualType CompoundType) {
John McCall526ab472011-10-25 17:37:35 +00007621 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7622
Chris Lattner326f7572008-11-18 01:30:42 +00007623 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007624 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007625 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007626
Richard Trieuda4f43a62011-09-07 01:33:52 +00007627 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007628 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7629 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007630 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007631 if (CompoundType.isNull()) {
Nico Weber33fd5232012-06-28 23:53:12 +00007632 Expr *RHSCheck = RHS.get();
7633
Nico Weberb8124d12012-07-03 02:03:06 +00007634 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber33fd5232012-06-28 23:53:12 +00007635
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007636 QualType LHSTy(LHSType);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007637 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007638 if (RHS.isInvalid())
7639 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007640 // Special case of NSObject attributes on c-style pointer types.
7641 if (ConvTy == IncompatiblePointer &&
7642 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007643 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007644 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007645 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007646 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007647
John McCall7decc9e2010-11-18 06:31:45 +00007648 if (ConvTy == Compatible &&
Fariborz Jahaniane2a77762012-01-24 19:40:13 +00007649 LHSType->isObjCObjectType())
Fariborz Jahanian3c4225a2012-01-24 18:05:45 +00007650 Diag(Loc, diag::err_objc_object_assignment)
7651 << LHSType;
John McCall7decc9e2010-11-18 06:31:45 +00007652
Chris Lattnerea714382008-08-21 18:04:13 +00007653 // If the RHS is a unary plus or minus, check to see if they = and + are
7654 // right next to each other. If so, the user may have typo'd "x =+ 4"
7655 // instead of "x += 4".
Chris Lattnerea714382008-08-21 18:04:13 +00007656 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7657 RHSCheck = ICE->getSubExpr();
7658 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007659 if ((UO->getOpcode() == UO_Plus ||
7660 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007661 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007662 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007663 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007664 // And there is a space or other character before the subexpr of the
7665 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007666 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007667 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007668 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007669 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007670 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007671 }
Chris Lattnerea714382008-08-21 18:04:13 +00007672 }
John McCall31168b02011-06-15 23:02:42 +00007673
7674 if (ConvTy == Compatible) {
7675 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007676 checkRetainCycles(LHSExpr, RHS.get());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007677 else if (getLangOpts().ObjCAutoRefCount)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007678 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007679 }
Chris Lattnerea714382008-08-21 18:04:13 +00007680 } else {
7681 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007682 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007683 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007684
Chris Lattner326f7572008-11-18 01:30:42 +00007685 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007686 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007687 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007688
Richard Trieuda4f43a62011-09-07 01:33:52 +00007689 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007690
Steve Naroff98cf3e92007-06-06 18:38:38 +00007691 // C99 6.5.16p3: The type of an assignment expression is the type of the
7692 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007693 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007694 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7695 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007696 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007697 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007698 return (getLangOpts().CPlusPlus
John McCall01cbf2d2010-10-12 02:19:57 +00007699 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007700}
7701
Chris Lattner326f7572008-11-18 01:30:42 +00007702// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007703static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007704 SourceLocation Loc) {
John McCall3aef3d82011-04-10 19:13:55 +00007705 LHS = S.CheckPlaceholderExpr(LHS.take());
7706 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007707 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007708 return QualType();
7709
John McCall73d36182010-10-12 07:14:40 +00007710 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7711 // operands, but not unary promotions.
7712 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007713
John McCall34376a62010-12-04 03:47:34 +00007714 // So we treat the LHS as a ignored value, and in C++ we allow the
7715 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007716 LHS = S.IgnoredValueConversions(LHS.take());
7717 if (LHS.isInvalid())
7718 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007719
Eli Friedmanc11535c2012-05-24 00:47:05 +00007720 S.DiagnoseUnusedExprResult(LHS.get());
7721
David Blaikiebbafb8a2012-03-11 07:00:24 +00007722 if (!S.getLangOpts().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007723 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7724 if (RHS.isInvalid())
7725 return QualType();
7726 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007727 S.RequireCompleteType(Loc, RHS.get()->getType(),
7728 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007729 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007730
John Wiegley01296292011-04-08 18:41:53 +00007731 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007732}
7733
Steve Naroff7a5af782007-07-13 16:58:59 +00007734/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7735/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007736static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7737 ExprValueKind &VK,
7738 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007739 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007740 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007741 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007742
Chris Lattner6b0cf142008-11-21 07:05:48 +00007743 QualType ResType = Op->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00007744 // Atomic types can be used for increment / decrement where the non-atomic
7745 // versions can, so ignore the _Atomic() specifier for the purpose of
7746 // checking.
7747 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7748 ResType = ResAtomicType->getValueType();
7749
Chris Lattner6b0cf142008-11-21 07:05:48 +00007750 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007751
David Blaikiebbafb8a2012-03-11 07:00:24 +00007752 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007753 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007754 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007755 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007756 return QualType();
7757 }
7758 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007759 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007760 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007761 // OK!
John McCallf2538342012-07-31 05:14:30 +00007762 } else if (ResType->isPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007763 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007764 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007765 return QualType();
John McCallf2538342012-07-31 05:14:30 +00007766 } else if (ResType->isObjCObjectPointerType()) {
7767 // On modern runtimes, ObjC pointer arithmetic is forbidden.
7768 // Otherwise, we just need a complete type.
7769 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7770 checkArithmeticOnObjCPointer(S, OpLoc, Op))
7771 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007772 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007773 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007774 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007775 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007776 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007777 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007778 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007779 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007780 IsInc, IsPrefix);
David Blaikiebbafb8a2012-03-11 07:00:24 +00007781 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00007782 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007783 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007784 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007785 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007786 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007787 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007788 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007789 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007790 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007791 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007792 // In C++, a prefix increment is the same type as the operand. Otherwise
7793 // (in C or with postfix), the increment is the unqualified type of the
7794 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007795 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007796 VK = VK_LValue;
7797 return ResType;
7798 } else {
7799 VK = VK_RValue;
7800 return ResType.getUnqualifiedType();
7801 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007802}
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007803
7804
Anders Carlsson806700f2008-02-01 07:15:58 +00007805/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007806/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007807/// where the declaration is needed for type checking. We only need to
7808/// handle cases when the expression references a function designator
7809/// or is an lvalue. Here are some examples:
7810/// - &(x) => x
7811/// - &*****f => f for f a function designator.
7812/// - &s.xx => s
7813/// - &s.zz[1].yy -> s, if zz is an array
7814/// - *(x + 1) -> x, if x is an array
7815/// - &"123"[2] -> 0
7816/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007817static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007818 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007819 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007820 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007821 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007822 // If this is an arrow operator, the address is an offset from
7823 // the base's value, so the object the base refers to is
7824 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007825 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007826 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007827 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007828 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007829 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007830 // FIXME: This code shouldn't be necessary! We should catch the implicit
7831 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007832 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7833 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7834 if (ICE->getSubExpr()->getType()->isArrayType())
7835 return getPrimaryDecl(ICE->getSubExpr());
7836 }
7837 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007838 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007839 case Stmt::UnaryOperatorClass: {
7840 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007841
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007842 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007843 case UO_Real:
7844 case UO_Imag:
7845 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007846 return getPrimaryDecl(UO->getSubExpr());
7847 default:
7848 return 0;
7849 }
7850 }
Steve Naroff47500512007-04-19 23:00:49 +00007851 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007852 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007853 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007854 // If the result of an implicit cast is an l-value, we care about
7855 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007856 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007857 default:
7858 return 0;
7859 }
7860}
7861
Richard Trieu5f376f62011-09-07 21:46:33 +00007862namespace {
7863 enum {
7864 AO_Bit_Field = 0,
7865 AO_Vector_Element = 1,
7866 AO_Property_Expansion = 2,
7867 AO_Register_Variable = 3,
7868 AO_No_Error = 4
7869 };
7870}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007871/// \brief Diagnose invalid operand for address of operations.
7872///
7873/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007874static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7875 Expr *E, unsigned Type) {
7876 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7877}
7878
Steve Naroff47500512007-04-19 23:00:49 +00007879/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007880/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007881/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007882/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007883/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007884/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007885/// we allow the '&' but retain the overloaded-function type.
John McCall526ab472011-10-25 17:37:35 +00007886static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall4bc41ae2010-11-18 19:01:18 +00007887 SourceLocation OpLoc) {
John McCall526ab472011-10-25 17:37:35 +00007888 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7889 if (PTy->getKind() == BuiltinType::Overload) {
7890 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7891 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7892 << OrigOp.get()->getSourceRange();
7893 return QualType();
7894 }
7895
7896 return S.Context.OverloadTy;
7897 }
7898
7899 if (PTy->getKind() == BuiltinType::UnknownAny)
7900 return S.Context.UnknownAnyTy;
7901
7902 if (PTy->getKind() == BuiltinType::BoundMember) {
7903 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7904 << OrigOp.get()->getSourceRange();
Douglas Gregor668d3622011-10-09 19:10:41 +00007905 return QualType();
7906 }
John McCall526ab472011-10-25 17:37:35 +00007907
7908 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7909 if (OrigOp.isInvalid()) return QualType();
John McCall0009fcc2011-04-26 20:42:42 +00007910 }
John McCall8d08b9b2010-08-27 09:08:28 +00007911
John McCall526ab472011-10-25 17:37:35 +00007912 if (OrigOp.get()->isTypeDependent())
7913 return S.Context.DependentTy;
7914
7915 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007916
John McCall8d08b9b2010-08-27 09:08:28 +00007917 // Make sure to ignore parentheses in subsequent checks
John McCall526ab472011-10-25 17:37:35 +00007918 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007919
David Blaikiebbafb8a2012-03-11 07:00:24 +00007920 if (S.getLangOpts().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007921 // Implement C99-only parts of addressof rules.
7922 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007923 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007924 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7925 // (assuming the deref expression is valid).
7926 return uOp->getSubExpr()->getType();
7927 }
7928 // Technically, there should be a check for array subscript
7929 // expressions here, but the result of one is always an lvalue anyway.
7930 }
John McCallf3a88602011-02-03 08:15:49 +00007931 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007932 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00007933 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00007934
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007935 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007936 bool sfinae = S.isSFINAEContext();
7937 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7938 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007939 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007940 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007941 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007942 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007943 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007944 } else if (lval == Expr::LV_MemberFunction) {
7945 // If it's an instance method, make a member pointer.
7946 // The expression must have exactly the form &A::foo.
7947
7948 // If the underlying expression isn't a decl ref, give up.
7949 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007950 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00007951 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00007952 return QualType();
7953 }
7954 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7955 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7956
7957 // The id-expression was parenthesized.
John McCall526ab472011-10-25 17:37:35 +00007958 if (OrigOp.get() != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007959 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00007960 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00007961
7962 // The method was named without a qualifier.
7963 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007964 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007965 << op->getSourceRange();
7966 }
7967
John McCall4bc41ae2010-11-18 19:01:18 +00007968 return S.Context.getMemberPointerType(op->getType(),
7969 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007970 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007971 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007972 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007973 if (!op->getType()->isFunctionType()) {
John McCall526ab472011-10-25 17:37:35 +00007974 // Use a special diagnostic for loads from property references.
John McCallfe96e0b2011-11-06 09:01:30 +00007975 if (isa<PseudoObjectExpr>(op)) {
John McCall526ab472011-10-25 17:37:35 +00007976 AddressOfError = AO_Property_Expansion;
7977 } else {
7978 // FIXME: emit more specific diag...
7979 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7980 << op->getSourceRange();
7981 return QualType();
7982 }
Steve Naroff35d85152007-05-07 00:24:15 +00007983 }
John McCall086a4642010-11-24 05:12:34 +00007984 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007985 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00007986 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00007987 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007988 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00007989 AddressOfError = AO_Vector_Element;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007990 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007991 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007992 // with the register storage-class specifier.
7993 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007994 // in C++ it is not error to take address of a register
7995 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007996 if (vd->getStorageClass() == SC_Register &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007997 !S.getLangOpts().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00007998 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00007999 }
John McCalld14a8642009-11-21 08:51:07 +00008000 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008001 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00008002 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00008003 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008004 // Could be a pointer to member, though, if there is an explicit
8005 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00008006 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008007 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008008 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00008009 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008010 S.Diag(OpLoc,
8011 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00008012 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008013 return QualType();
8014 }
Mike Stump11289f42009-09-09 15:08:12 +00008015
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00008016 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8017 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00008018 return S.Context.getMemberPointerType(op->getType(),
8019 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00008020 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008021 }
Eli Friedman755c0c92011-08-26 20:28:17 +00008022 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00008023 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00008024 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008025
Richard Trieu5f376f62011-09-07 21:46:33 +00008026 if (AddressOfError != AO_No_Error) {
8027 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8028 return QualType();
8029 }
8030
Eli Friedmance7f9002009-05-16 23:27:50 +00008031 if (lval == Expr::LV_IncompleteVoidType) {
8032 // Taking the address of a void variable is technically illegal, but we
8033 // allow it in cases which are otherwise valid.
8034 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00008035 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00008036 }
8037
Steve Naroff47500512007-04-19 23:00:49 +00008038 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00008039 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00008040 return S.Context.getObjCObjectPointerType(op->getType());
8041 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00008042}
8043
Chris Lattner9156f1b2010-07-05 19:17:26 +00008044/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00008045static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8046 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008047 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008048 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008049
John Wiegley01296292011-04-08 18:41:53 +00008050 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8051 if (ConvResult.isInvalid())
8052 return QualType();
8053 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00008054 QualType OpTy = Op->getType();
8055 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00008056
8057 if (isa<CXXReinterpretCastExpr>(Op)) {
8058 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8059 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8060 Op->getSourceRange());
8061 }
8062
Chris Lattner9156f1b2010-07-05 19:17:26 +00008063 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8064 // is an incomplete type or void. It would be possible to warn about
8065 // dereferencing a void pointer, but it's completely well-defined, and such a
8066 // warning is unlikely to catch any mistakes.
8067 if (const PointerType *PT = OpTy->getAs<PointerType>())
8068 Result = PT->getPointeeType();
8069 else if (const ObjCObjectPointerType *OPT =
8070 OpTy->getAs<ObjCObjectPointerType>())
8071 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00008072 else {
John McCall3aef3d82011-04-10 19:13:55 +00008073 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008074 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008075 if (PR.take() != Op)
8076 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008077 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008078
Chris Lattner9156f1b2010-07-05 19:17:26 +00008079 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008080 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00008081 << OpTy << Op->getSourceRange();
8082 return QualType();
8083 }
John McCall4bc41ae2010-11-18 19:01:18 +00008084
8085 // Dereferences are usually l-values...
8086 VK = VK_LValue;
8087
8088 // ...except that certain expressions are never l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008089 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00008090 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00008091
8092 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00008093}
Steve Naroff218bc2b2007-05-04 21:54:46 +00008094
John McCalle3027922010-08-25 11:45:40 +00008095static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00008096 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008097 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008098 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00008099 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00008100 case tok::periodstar: Opc = BO_PtrMemD; break;
8101 case tok::arrowstar: Opc = BO_PtrMemI; break;
8102 case tok::star: Opc = BO_Mul; break;
8103 case tok::slash: Opc = BO_Div; break;
8104 case tok::percent: Opc = BO_Rem; break;
8105 case tok::plus: Opc = BO_Add; break;
8106 case tok::minus: Opc = BO_Sub; break;
8107 case tok::lessless: Opc = BO_Shl; break;
8108 case tok::greatergreater: Opc = BO_Shr; break;
8109 case tok::lessequal: Opc = BO_LE; break;
8110 case tok::less: Opc = BO_LT; break;
8111 case tok::greaterequal: Opc = BO_GE; break;
8112 case tok::greater: Opc = BO_GT; break;
8113 case tok::exclaimequal: Opc = BO_NE; break;
8114 case tok::equalequal: Opc = BO_EQ; break;
8115 case tok::amp: Opc = BO_And; break;
8116 case tok::caret: Opc = BO_Xor; break;
8117 case tok::pipe: Opc = BO_Or; break;
8118 case tok::ampamp: Opc = BO_LAnd; break;
8119 case tok::pipepipe: Opc = BO_LOr; break;
8120 case tok::equal: Opc = BO_Assign; break;
8121 case tok::starequal: Opc = BO_MulAssign; break;
8122 case tok::slashequal: Opc = BO_DivAssign; break;
8123 case tok::percentequal: Opc = BO_RemAssign; break;
8124 case tok::plusequal: Opc = BO_AddAssign; break;
8125 case tok::minusequal: Opc = BO_SubAssign; break;
8126 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8127 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8128 case tok::ampequal: Opc = BO_AndAssign; break;
8129 case tok::caretequal: Opc = BO_XorAssign; break;
8130 case tok::pipeequal: Opc = BO_OrAssign; break;
8131 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008132 }
8133 return Opc;
8134}
8135
John McCalle3027922010-08-25 11:45:40 +00008136static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008137 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008138 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008139 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00008140 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008141 case tok::plusplus: Opc = UO_PreInc; break;
8142 case tok::minusminus: Opc = UO_PreDec; break;
8143 case tok::amp: Opc = UO_AddrOf; break;
8144 case tok::star: Opc = UO_Deref; break;
8145 case tok::plus: Opc = UO_Plus; break;
8146 case tok::minus: Opc = UO_Minus; break;
8147 case tok::tilde: Opc = UO_Not; break;
8148 case tok::exclaim: Opc = UO_LNot; break;
8149 case tok::kw___real: Opc = UO_Real; break;
8150 case tok::kw___imag: Opc = UO_Imag; break;
8151 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008152 }
8153 return Opc;
8154}
8155
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008156/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8157/// This warning is only emitted for builtin assignment operations. It is also
8158/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00008159static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008160 SourceLocation OpLoc) {
8161 if (!S.ActiveTemplateInstantiations.empty())
8162 return;
8163 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8164 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008165 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8166 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8167 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8168 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8169 if (!LHSDeclRef || !RHSDeclRef ||
8170 LHSDeclRef->getLocation().isMacroID() ||
8171 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008172 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008173 const ValueDecl *LHSDecl =
8174 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8175 const ValueDecl *RHSDecl =
8176 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8177 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008178 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008179 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008180 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008181 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008182 if (RefTy->getPointeeType().isVolatileQualified())
8183 return;
8184
8185 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00008186 << LHSDeclRef->getType()
8187 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008188}
8189
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008190/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8191/// operator @p Opc at location @c TokLoc. This routine only supports
8192/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008193ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008194 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008195 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008196 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl67766732012-02-27 20:34:02 +00008197 // The syntax only allows initializer lists on the RHS of assignment,
8198 // so we don't need to worry about accepting invalid code for
8199 // non-assignment operators.
8200 // C++11 5.17p9:
8201 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8202 // of x = {} is x = T().
8203 InitializationKind Kind =
8204 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8205 InitializedEntity Entity =
8206 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8207 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008208 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl67766732012-02-27 20:34:02 +00008209 if (Init.isInvalid())
8210 return Init;
8211 RHSExpr = Init.take();
8212 }
8213
Richard Trieu4a287fb2011-09-07 01:49:20 +00008214 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008215 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008216 // The following two variables are used for compound assignment operators
8217 QualType CompLHSTy; // Type of LHS after promotions for computation
8218 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008219 ExprValueKind VK = VK_RValue;
8220 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008221
8222 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008223 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008224 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008225 if (getLangOpts().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00008226 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8227 VK = LHS.get()->getValueKind();
8228 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008229 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008230 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008231 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008232 break;
John McCalle3027922010-08-25 11:45:40 +00008233 case BO_PtrMemD:
8234 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008235 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008236 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008237 break;
John McCalle3027922010-08-25 11:45:40 +00008238 case BO_Mul:
8239 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008240 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008241 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008242 break;
John McCalle3027922010-08-25 11:45:40 +00008243 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008244 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008245 break;
John McCalle3027922010-08-25 11:45:40 +00008246 case BO_Add:
Nico Weberccec40d2012-03-02 22:01:22 +00008247 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008248 break;
John McCalle3027922010-08-25 11:45:40 +00008249 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008250 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008251 break;
John McCalle3027922010-08-25 11:45:40 +00008252 case BO_Shl:
8253 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008254 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008255 break;
John McCalle3027922010-08-25 11:45:40 +00008256 case BO_LE:
8257 case BO_LT:
8258 case BO_GE:
8259 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008260 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008261 break;
John McCalle3027922010-08-25 11:45:40 +00008262 case BO_EQ:
8263 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008264 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008265 break;
John McCalle3027922010-08-25 11:45:40 +00008266 case BO_And:
8267 case BO_Xor:
8268 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008269 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008270 break;
John McCalle3027922010-08-25 11:45:40 +00008271 case BO_LAnd:
8272 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008273 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008274 break;
John McCalle3027922010-08-25 11:45:40 +00008275 case BO_MulAssign:
8276 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008277 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008278 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008279 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008280 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8281 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008282 break;
John McCalle3027922010-08-25 11:45:40 +00008283 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008284 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008285 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008286 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8287 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008288 break;
John McCalle3027922010-08-25 11:45:40 +00008289 case BO_AddAssign:
Nico Weberccec40d2012-03-02 22:01:22 +00008290 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu4a287fb2011-09-07 01:49:20 +00008291 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8292 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008293 break;
John McCalle3027922010-08-25 11:45:40 +00008294 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008295 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8296 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8297 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008298 break;
John McCalle3027922010-08-25 11:45:40 +00008299 case BO_ShlAssign:
8300 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008301 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008302 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008303 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8304 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008305 break;
John McCalle3027922010-08-25 11:45:40 +00008306 case BO_AndAssign:
8307 case BO_XorAssign:
8308 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008309 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008310 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008311 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8312 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008313 break;
John McCalle3027922010-08-25 11:45:40 +00008314 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008315 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikiebbafb8a2012-03-11 07:00:24 +00008316 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu4a287fb2011-09-07 01:49:20 +00008317 VK = RHS.get()->getValueKind();
8318 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008319 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008320 break;
8321 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008322 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008323 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008324
8325 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00008326 CheckArrayAccess(LHS.get());
8327 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008328
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008329 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008330 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008331 ResultTy, VK, OK, OpLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00008332 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00008333 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008334 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008335 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008336 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008337 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008338 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00008339 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008340}
8341
Sebastian Redl44615072009-10-27 12:10:02 +00008342/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8343/// operators are mixed in a way that suggests that the programmer forgot that
8344/// comparison operators have higher precedence. The most typical example of
8345/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008346static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008347 SourceLocation OpLoc, Expr *LHSExpr,
8348 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00008349 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008350 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8351 RHSopc = static_cast<BinOp::Opcode>(-1);
8352 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8353 LHSopc = BO->getOpcode();
8354 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8355 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00008356
8357 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008358 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00008359 return;
8360
8361 // Bitwise operations are sometimes used as eager logical ops.
8362 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008363 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8364 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008365 return;
8366
Richard Trieu4a287fb2011-09-07 01:49:20 +00008367 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8368 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008369 if (!isLeftComp && !isRightComp) return;
8370
Richard Trieu4a287fb2011-09-07 01:49:20 +00008371 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8372 OpLoc)
8373 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8374 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8375 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008376 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00008377 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8378 RHSExpr->getLocEnd())
8379 : SourceRange(LHSExpr->getLocStart(),
8380 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00008381
8382 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8383 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8384 SuggestParentheses(Self, OpLoc,
8385 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Nico Webercdfb1ae2012-06-03 07:07:00 +00008386 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00008387 SuggestParentheses(Self, OpLoc,
8388 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8389 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00008390}
8391
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008392/// \brief It accepts a '&' expr that is inside a '|' one.
8393/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8394/// in parentheses.
8395static void
8396EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8397 BinaryOperator *Bop) {
8398 assert(Bop->getOpcode() == BO_And);
8399 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8400 << Bop->getSourceRange() << OpLoc;
8401 SuggestParentheses(Self, Bop->getOperatorLoc(),
8402 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8403 Bop->getSourceRange());
8404}
8405
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008406/// \brief It accepts a '&&' expr that is inside a '||' one.
8407/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8408/// in parentheses.
8409static void
8410EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008411 BinaryOperator *Bop) {
8412 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008413 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8414 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008415 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008416 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008417 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008418}
8419
8420/// \brief Returns true if the given expression can be evaluated as a constant
8421/// 'true'.
8422static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8423 bool Res;
8424 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8425}
8426
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008427/// \brief Returns true if the given expression can be evaluated as a constant
8428/// 'false'.
8429static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8430 bool Res;
8431 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8432}
8433
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008434/// \brief Look for '&&' in the left hand of a '||' expr.
8435static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008436 Expr *LHSExpr, Expr *RHSExpr) {
8437 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008438 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008439 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008440 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008441 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008442 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8443 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8444 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8445 } else if (Bop->getOpcode() == BO_LOr) {
8446 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8447 // If it's "a || b && 1 || c" we didn't warn earlier for
8448 // "a || b && 1", but warn now.
8449 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8450 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8451 }
8452 }
8453 }
8454}
8455
8456/// \brief Look for '&&' in the right hand of a '||' expr.
8457static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008458 Expr *LHSExpr, Expr *RHSExpr) {
8459 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008460 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008461 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008462 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008463 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008464 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8465 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8466 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008467 }
8468 }
8469}
8470
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008471/// \brief Look for '&' in the left or right hand of a '|' expr.
8472static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8473 Expr *OrArg) {
8474 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8475 if (Bop->getOpcode() == BO_And)
8476 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8477 }
8478}
8479
Sebastian Redl43028242009-10-26 15:24:15 +00008480/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008481/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008482static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008483 SourceLocation OpLoc, Expr *LHSExpr,
8484 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008485 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008486 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008487 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008488
8489 // Diagnose "arg1 & arg2 | arg3"
8490 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008491 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8492 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008493 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008494
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008495 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8496 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008497 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008498 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8499 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008500 }
Sebastian Redl43028242009-10-26 15:24:15 +00008501}
8502
Steve Naroff218bc2b2007-05-04 21:54:46 +00008503// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008504ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008505 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008506 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008507 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008508 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8509 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008510
Sebastian Redl43028242009-10-26 15:24:15 +00008511 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008512 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008513
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008514 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008515}
8516
John McCall526ab472011-10-25 17:37:35 +00008517/// Build an overloaded binary operator expression in the given scope.
8518static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8519 BinaryOperatorKind Opc,
8520 Expr *LHS, Expr *RHS) {
8521 // Find all of the overloaded operators visible from this
8522 // point. We perform both an operator-name lookup from the local
8523 // scope and an argument-dependent lookup based on the types of
8524 // the arguments.
8525 UnresolvedSet<16> Functions;
8526 OverloadedOperatorKind OverOp
8527 = BinaryOperator::getOverloadedOperator(Opc);
8528 if (Sc && OverOp != OO_None)
8529 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8530 RHS->getType(), Functions);
8531
8532 // Build the (potentially-overloaded, potentially-dependent)
8533 // binary operation.
8534 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8535}
8536
John McCalldadc5752010-08-24 06:29:42 +00008537ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008538 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008539 Expr *LHSExpr, Expr *RHSExpr) {
John McCall9a43e122011-10-28 01:04:34 +00008540 // We want to end up calling one of checkPseudoObjectAssignment
8541 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8542 // both expressions are overloadable or either is type-dependent),
8543 // or CreateBuiltinBinOp (in any other case). We also want to get
8544 // any placeholder types out of the way.
8545
John McCall526ab472011-10-25 17:37:35 +00008546 // Handle pseudo-objects in the LHS.
8547 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8548 // Assignments with a pseudo-object l-value need special analysis.
8549 if (pty->getKind() == BuiltinType::PseudoObject &&
8550 BinaryOperator::isAssignmentOp(Opc))
8551 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8552
8553 // Don't resolve overloads if the other type is overloadable.
8554 if (pty->getKind() == BuiltinType::Overload) {
8555 // We can't actually test that if we still have a placeholder,
8556 // though. Fortunately, none of the exceptions we see in that
John McCall9a43e122011-10-28 01:04:34 +00008557 // code below are valid when the LHS is an overload set. Note
8558 // that an overload set can be dependently-typed, but it never
8559 // instantiates to having an overloadable type.
John McCall526ab472011-10-25 17:37:35 +00008560 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8561 if (resolvedRHS.isInvalid()) return ExprError();
8562 RHSExpr = resolvedRHS.take();
8563
John McCall9a43e122011-10-28 01:04:34 +00008564 if (RHSExpr->isTypeDependent() ||
8565 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008566 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8567 }
8568
8569 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8570 if (LHS.isInvalid()) return ExprError();
8571 LHSExpr = LHS.take();
8572 }
8573
8574 // Handle pseudo-objects in the RHS.
8575 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8576 // An overload in the RHS can potentially be resolved by the type
8577 // being assigned to.
John McCall9a43e122011-10-28 01:04:34 +00008578 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8579 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8580 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8581
Eli Friedman419b1ff2012-01-17 21:27:43 +00008582 if (LHSExpr->getType()->isOverloadableType())
8583 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8584
John McCall526ab472011-10-25 17:37:35 +00008585 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCall9a43e122011-10-28 01:04:34 +00008586 }
John McCall526ab472011-10-25 17:37:35 +00008587
8588 // Don't resolve overloads if the other type is overloadable.
8589 if (pty->getKind() == BuiltinType::Overload &&
8590 LHSExpr->getType()->isOverloadableType())
8591 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8592
8593 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8594 if (!resolvedRHS.isUsable()) return ExprError();
8595 RHSExpr = resolvedRHS.take();
8596 }
8597
David Blaikiebbafb8a2012-03-11 07:00:24 +00008598 if (getLangOpts().CPlusPlus) {
John McCall9a43e122011-10-28 01:04:34 +00008599 // If either expression is type-dependent, always build an
8600 // overloaded op.
8601 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8602 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008603
John McCall9a43e122011-10-28 01:04:34 +00008604 // Otherwise, build an overloaded op if either expression has an
8605 // overloadable type.
8606 if (LHSExpr->getType()->isOverloadableType() ||
8607 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008608 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb5d49352009-01-19 22:31:54 +00008609 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008610
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008611 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008612 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008613}
8614
John McCalldadc5752010-08-24 06:29:42 +00008615ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008616 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008617 Expr *InputExpr) {
8618 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008619 ExprValueKind VK = VK_RValue;
8620 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008621 QualType resultType;
8622 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008623 case UO_PreInc:
8624 case UO_PreDec:
8625 case UO_PostInc:
8626 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008627 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008628 Opc == UO_PreInc ||
8629 Opc == UO_PostInc,
8630 Opc == UO_PreInc ||
8631 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008632 break;
John McCalle3027922010-08-25 11:45:40 +00008633 case UO_AddrOf:
John McCall526ab472011-10-25 17:37:35 +00008634 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008635 break;
John McCall31996342011-04-07 08:22:57 +00008636 case UO_Deref: {
John Wiegley01296292011-04-08 18:41:53 +00008637 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8638 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008639 break;
John McCall31996342011-04-07 08:22:57 +00008640 }
John McCalle3027922010-08-25 11:45:40 +00008641 case UO_Plus:
8642 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008643 Input = UsualUnaryConversions(Input.take());
8644 if (Input.isInvalid()) return ExprError();
8645 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008646 if (resultType->isDependentType())
8647 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008648 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8649 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008650 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008651 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregord08452f2008-11-19 15:42:04 +00008652 resultType->isEnumeralType())
8653 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008654 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008655 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008656 resultType->isPointerType())
8657 break;
8658
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008659 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008660 << resultType << Input.get()->getSourceRange());
8661
John McCalle3027922010-08-25 11:45:40 +00008662 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008663 Input = UsualUnaryConversions(Input.take());
8664 if (Input.isInvalid()) return ExprError();
8665 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008666 if (resultType->isDependentType())
8667 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008668 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8669 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8670 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008671 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008672 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008673 else if (resultType->hasIntegerRepresentation())
8674 break;
John McCall526ab472011-10-25 17:37:35 +00008675 else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008676 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008677 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008678 }
Steve Naroff35d85152007-05-07 00:24:15 +00008679 break;
John Wiegley01296292011-04-08 18:41:53 +00008680
John McCalle3027922010-08-25 11:45:40 +00008681 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008682 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008683 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8684 if (Input.isInvalid()) return ExprError();
8685 resultType = Input.get()->getType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00008686
8687 // Though we still have to promote half FP to float...
8688 if (resultType->isHalfType()) {
8689 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8690 resultType = Context.FloatTy;
8691 }
8692
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008693 if (resultType->isDependentType())
8694 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008695 if (resultType->isScalarType()) {
8696 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008697 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008698 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8699 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008700 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8701 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008702 }
Tanya Lattner3dd33b22012-01-19 01:16:16 +00008703 } else if (resultType->isExtVectorType()) {
Tanya Lattner20248222012-01-16 21:02:28 +00008704 // Vector logical not returns the signed variant of the operand type.
8705 resultType = GetSignedVectorType(resultType);
8706 break;
John McCall36226622010-10-12 02:09:17 +00008707 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008708 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008709 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008710 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008711
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008712 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008713 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008714 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008715 break;
John McCalle3027922010-08-25 11:45:40 +00008716 case UO_Real:
8717 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008718 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smith0b6b8e42012-02-18 20:53:32 +00008719 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8720 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley01296292011-04-08 18:41:53 +00008721 if (Input.isInvalid()) return ExprError();
Richard Smith0b6b8e42012-02-18 20:53:32 +00008722 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8723 if (Input.get()->getValueKind() != VK_RValue &&
8724 Input.get()->getObjectKind() == OK_Ordinary)
8725 VK = Input.get()->getValueKind();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008726 } else if (!getLangOpts().CPlusPlus) {
Richard Smith0b6b8e42012-02-18 20:53:32 +00008727 // In C, a volatile scalar is read by __imag. In C++, it is not.
8728 Input = DefaultLvalueConversion(Input.take());
8729 }
Chris Lattner30b5dd02007-08-24 21:16:53 +00008730 break;
John McCalle3027922010-08-25 11:45:40 +00008731 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008732 resultType = Input.get()->getType();
8733 VK = Input.get()->getValueKind();
8734 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008735 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008736 }
John Wiegley01296292011-04-08 18:41:53 +00008737 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008738 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008739
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008740 // Check for array bounds violations in the operand of the UnaryOperator,
8741 // except for the '*' and '&' operators that have to be handled specially
8742 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8743 // that are explicitly defined as valid by the standard).
8744 if (Opc != UO_AddrOf && Opc != UO_Deref)
8745 CheckArrayAccess(Input.get());
8746
John Wiegley01296292011-04-08 18:41:53 +00008747 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008748 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008749}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008750
Douglas Gregor72341032011-12-14 21:23:13 +00008751/// \brief Determine whether the given expression is a qualified member
8752/// access expression, of a form that could be turned into a pointer to member
8753/// with the address-of operator.
8754static bool isQualifiedMemberAccess(Expr *E) {
8755 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8756 if (!DRE->getQualifier())
8757 return false;
8758
8759 ValueDecl *VD = DRE->getDecl();
8760 if (!VD->isCXXClassMember())
8761 return false;
8762
8763 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8764 return true;
8765 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8766 return Method->isInstance();
8767
8768 return false;
8769 }
8770
8771 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8772 if (!ULE->getQualifier())
8773 return false;
8774
8775 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8776 DEnd = ULE->decls_end();
8777 D != DEnd; ++D) {
8778 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8779 if (Method->isInstance())
8780 return true;
8781 } else {
8782 // Overload set does not contain methods.
8783 break;
8784 }
8785 }
8786
8787 return false;
8788 }
8789
8790 return false;
8791}
8792
John McCalldadc5752010-08-24 06:29:42 +00008793ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008794 UnaryOperatorKind Opc, Expr *Input) {
John McCall526ab472011-10-25 17:37:35 +00008795 // First things first: handle placeholders so that the
8796 // overloaded-operator check considers the right type.
8797 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8798 // Increment and decrement of pseudo-object references.
8799 if (pty->getKind() == BuiltinType::PseudoObject &&
8800 UnaryOperator::isIncrementDecrementOp(Opc))
8801 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8802
8803 // extension is always a builtin operator.
8804 if (Opc == UO_Extension)
8805 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8806
8807 // & gets special logic for several kinds of placeholder.
8808 // The builtin code knows what to do.
8809 if (Opc == UO_AddrOf &&
8810 (pty->getKind() == BuiltinType::Overload ||
8811 pty->getKind() == BuiltinType::UnknownAny ||
8812 pty->getKind() == BuiltinType::BoundMember))
8813 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8814
8815 // Anything else needs to be handled now.
8816 ExprResult Result = CheckPlaceholderExpr(Input);
8817 if (Result.isInvalid()) return ExprError();
8818 Input = Result.take();
8819 }
8820
David Blaikiebbafb8a2012-03-11 07:00:24 +00008821 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregor72341032011-12-14 21:23:13 +00008822 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8823 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008824 // Find all of the overloaded operators visible from this
8825 // point. We perform both an operator-name lookup from the local
8826 // scope and an argument-dependent lookup based on the types of
8827 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008828 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008829 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008830 if (S && OverOp != OO_None)
8831 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8832 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008833
John McCallb268a282010-08-23 23:25:46 +00008834 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008835 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008836
John McCallb268a282010-08-23 23:25:46 +00008837 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008838}
8839
Douglas Gregor5287f092009-11-05 00:51:44 +00008840// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008841ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008842 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008843 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008844}
8845
Steve Naroff66356bd2007-09-16 14:56:35 +00008846/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008847ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008848 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008849 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008850 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008851 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008852 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008853}
8854
John McCall31168b02011-06-15 23:02:42 +00008855/// Given the last statement in a statement-expression, check whether
8856/// the result is a producing expression (like a call to an
8857/// ns_returns_retained function) and, if so, rebuild it to hoist the
8858/// release out of the full-expression. Otherwise, return null.
8859/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008860static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008861 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008862 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008863 if (!cleanups) return 0;
8864
8865 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008866 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008867 return 0;
8868
8869 // Splice out the cast. This shouldn't modify any interesting
8870 // features of the statement.
8871 Expr *producer = cast->getSubExpr();
8872 assert(producer->getType() == cast->getType());
8873 assert(producer->getValueKind() == cast->getValueKind());
8874 cleanups->setSubExpr(producer);
8875 return cleanups;
8876}
8877
John McCall3abee492012-04-04 01:27:53 +00008878void Sema::ActOnStartStmtExpr() {
8879 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8880}
8881
8882void Sema::ActOnStmtExprError() {
John McCalled7b2782012-04-06 18:20:53 +00008883 // Note that function is also called by TreeTransform when leaving a
8884 // StmtExpr scope without rebuilding anything.
8885
John McCall3abee492012-04-04 01:27:53 +00008886 DiscardCleanupsInEvaluationContext();
8887 PopExpressionEvaluationContext();
8888}
8889
John McCalldadc5752010-08-24 06:29:42 +00008890ExprResult
John McCallb268a282010-08-23 23:25:46 +00008891Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008892 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008893 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8894 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8895
John McCall3abee492012-04-04 01:27:53 +00008896 if (hasAnyUnrecoverableErrorsInThisFunction())
8897 DiscardCleanupsInEvaluationContext();
8898 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8899 PopExpressionEvaluationContext();
8900
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008901 bool isFileScope
8902 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008903 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008904 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008905
Chris Lattner366727f2007-07-24 16:58:17 +00008906 // FIXME: there are a variety of strange constraints to enforce here, for
8907 // example, it is not possible to goto into a stmt expression apparently.
8908 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008909
Chris Lattner366727f2007-07-24 16:58:17 +00008910 // If there are sub stmts in the compound stmt, take the type of the last one
8911 // as the type of the stmtexpr.
8912 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008913 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008914 if (!Compound->body_empty()) {
8915 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008916 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008917 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008918 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8919 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008920 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008921 }
John McCall31168b02011-06-15 23:02:42 +00008922
John Wiegley01296292011-04-08 18:41:53 +00008923 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008924 // Do function/array conversion on the last expression, but not
8925 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008926 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8927 if (LastExpr.isInvalid())
8928 return ExprError();
8929 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008930
John Wiegley01296292011-04-08 18:41:53 +00008931 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008932 // In ARC, if the final expression ends in a consume, splice
8933 // the consume out and bind it later. In the alternate case
8934 // (when dealing with a retainable type), the result
8935 // initialization will create a produce. In both cases the
8936 // result will be +1, and we'll need to balance that out with
8937 // a bind.
8938 if (Expr *rebuiltLastStmt
8939 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8940 LastExpr = rebuiltLastStmt;
8941 } else {
8942 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008943 InitializedEntity::InitializeResult(LPLoc,
8944 Ty,
8945 false),
8946 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008947 LastExpr);
8948 }
8949
John Wiegley01296292011-04-08 18:41:53 +00008950 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008951 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008952 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008953 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008954 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008955 else
John Wiegley01296292011-04-08 18:41:53 +00008956 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008957 StmtExprMayBindToTemp = true;
8958 }
8959 }
8960 }
Chris Lattner944d3062008-07-26 19:51:01 +00008961 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008962
Eli Friedmanba961a92009-03-23 00:24:07 +00008963 // FIXME: Check that expression type is complete/non-abstract; statement
8964 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008965 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8966 if (StmtExprMayBindToTemp)
8967 return MaybeBindToTemporary(ResStmtExpr);
8968 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008969}
Steve Naroff78864672007-08-01 22:05:33 +00008970
John McCalldadc5752010-08-24 06:29:42 +00008971ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008972 TypeSourceInfo *TInfo,
8973 OffsetOfComponent *CompPtr,
8974 unsigned NumComponents,
8975 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008976 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008977 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008978 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008979
Chris Lattnerf17bd422007-08-30 17:45:32 +00008980 // We must have at least one component that refers to the type, and the first
8981 // one is known to be a field designator. Verify that the ArgTy represents
8982 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008983 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008984 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8985 << ArgTy << TypeRange);
8986
8987 // Type must be complete per C99 7.17p3 because a declaring a variable
8988 // with an incomplete type would be ill-formed.
8989 if (!Dependent
8990 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008991 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor882211c2010-04-28 22:16:22 +00008992 return ExprError();
8993
Chris Lattner78502cf2007-08-31 21:49:13 +00008994 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8995 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008996 // FIXME: This diagnostic isn't actually visible because the location is in
8997 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008998 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008999 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9000 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00009001
9002 bool DidWarnAboutNonPOD = false;
9003 QualType CurrentType = ArgTy;
9004 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009005 SmallVector<OffsetOfNode, 4> Comps;
9006 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00009007 for (unsigned i = 0; i != NumComponents; ++i) {
9008 const OffsetOfComponent &OC = CompPtr[i];
9009 if (OC.isBrackets) {
9010 // Offset of an array sub-field. TODO: Should we allow vector elements?
9011 if (!CurrentType->isDependentType()) {
9012 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9013 if(!AT)
9014 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9015 << CurrentType);
9016 CurrentType = AT->getElementType();
9017 } else
9018 CurrentType = Context.DependentTy;
9019
Richard Smith9fcc5c32011-10-17 23:29:39 +00009020 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9021 if (IdxRval.isInvalid())
9022 return ExprError();
9023 Expr *Idx = IdxRval.take();
9024
Douglas Gregor882211c2010-04-28 22:16:22 +00009025 // The expression must be an integral expression.
9026 // FIXME: An integral constant expression?
Douglas Gregor882211c2010-04-28 22:16:22 +00009027 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9028 !Idx->getType()->isIntegerType())
9029 return ExprError(Diag(Idx->getLocStart(),
9030 diag::err_typecheck_subscript_not_integer)
9031 << Idx->getSourceRange());
Richard Smitheda612882011-10-17 05:48:07 +00009032
Douglas Gregor882211c2010-04-28 22:16:22 +00009033 // Record this array index.
9034 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smith9fcc5c32011-10-17 23:29:39 +00009035 Exprs.push_back(Idx);
Douglas Gregor882211c2010-04-28 22:16:22 +00009036 continue;
9037 }
9038
9039 // Offset of a field.
9040 if (CurrentType->isDependentType()) {
9041 // We have the offset of a field, but we can't look into the dependent
9042 // type. Just record the identifier of the field.
9043 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9044 CurrentType = Context.DependentTy;
9045 continue;
9046 }
9047
9048 // We need to have a complete type to look into.
9049 if (RequireCompleteType(OC.LocStart, CurrentType,
9050 diag::err_offsetof_incomplete_type))
9051 return ExprError();
9052
9053 // Look for the designated field.
9054 const RecordType *RC = CurrentType->getAs<RecordType>();
9055 if (!RC)
9056 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9057 << CurrentType);
9058 RecordDecl *RD = RC->getDecl();
9059
9060 // C++ [lib.support.types]p5:
9061 // The macro offsetof accepts a restricted set of type arguments in this
9062 // International Standard. type shall be a POD structure or a POD union
9063 // (clause 9).
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009064 // C++11 [support.types]p4:
9065 // If type is not a standard-layout class (Clause 9), the results are
9066 // undefined.
Douglas Gregor882211c2010-04-28 22:16:22 +00009067 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009068 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9069 unsigned DiagID =
9070 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9071 : diag::warn_offsetof_non_pod_type;
9072
9073 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00009074 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009075 PDiag(DiagID)
Douglas Gregor882211c2010-04-28 22:16:22 +00009076 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9077 << CurrentType))
9078 DidWarnAboutNonPOD = true;
9079 }
9080
9081 // Look for the field.
9082 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9083 LookupQualifiedName(R, RD);
9084 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009085 IndirectFieldDecl *IndirectMemberDecl = 0;
9086 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00009087 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00009088 MemberDecl = IndirectMemberDecl->getAnonField();
9089 }
9090
Douglas Gregor882211c2010-04-28 22:16:22 +00009091 if (!MemberDecl)
9092 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9093 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9094 OC.LocEnd));
9095
Douglas Gregor10982ea2010-04-28 22:36:06 +00009096 // C99 7.17p3:
9097 // (If the specified member is a bit-field, the behavior is undefined.)
9098 //
9099 // We diagnose this as an error.
Richard Smithcaf33902011-10-10 18:28:20 +00009100 if (MemberDecl->isBitField()) {
Douglas Gregor10982ea2010-04-28 22:36:06 +00009101 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9102 << MemberDecl->getDeclName()
9103 << SourceRange(BuiltinLoc, RParenLoc);
9104 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9105 return ExprError();
9106 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009107
9108 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009109 if (IndirectMemberDecl)
9110 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009111
Douglas Gregord1702062010-04-29 00:18:15 +00009112 // If the member was found in a base class, introduce OffsetOfNodes for
9113 // the base class indirections.
9114 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9115 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009116 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00009117 CXXBasePath &Path = Paths.front();
9118 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9119 B != BEnd; ++B)
9120 Comps.push_back(OffsetOfNode(B->Base));
9121 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009122
Francois Pichet783dd6e2010-11-21 06:08:52 +00009123 if (IndirectMemberDecl) {
9124 for (IndirectFieldDecl::chain_iterator FI =
9125 IndirectMemberDecl->chain_begin(),
9126 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9127 assert(isa<FieldDecl>(*FI));
9128 Comps.push_back(OffsetOfNode(OC.LocStart,
9129 cast<FieldDecl>(*FI), OC.LocEnd));
9130 }
9131 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00009132 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00009133
Douglas Gregor882211c2010-04-28 22:16:22 +00009134 CurrentType = MemberDecl->getType().getNonReferenceType();
9135 }
9136
9137 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00009138 TInfo, Comps, Exprs, RParenLoc));
Douglas Gregor882211c2010-04-28 22:16:22 +00009139}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009140
John McCalldadc5752010-08-24 06:29:42 +00009141ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00009142 SourceLocation BuiltinLoc,
9143 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009144 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00009145 OffsetOfComponent *CompPtr,
9146 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009147 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00009148
Douglas Gregor882211c2010-04-28 22:16:22 +00009149 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009150 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00009151 if (ArgTy.isNull())
9152 return ExprError();
9153
Eli Friedman06dcfd92010-08-05 10:15:45 +00009154 if (!ArgTInfo)
9155 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9156
9157 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009158 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00009159}
9160
9161
John McCalldadc5752010-08-24 06:29:42 +00009162ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009163 Expr *CondExpr,
9164 Expr *LHSExpr, Expr *RHSExpr,
9165 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00009166 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9167
John McCall7decc9e2010-11-18 06:31:45 +00009168 ExprValueKind VK = VK_RValue;
9169 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009170 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00009171 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00009172 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009173 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00009174 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009175 } else {
9176 // The conditional expression is required to be a constant expression.
9177 llvm::APSInt condEval(32);
Douglas Gregore2b37442012-05-04 22:38:52 +00009178 ExprResult CondICE
9179 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9180 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009181 if (CondICE.isInvalid())
9182 return ExprError();
9183 CondExpr = CondICE.take();
Steve Naroff9efdabc2007-08-03 21:21:27 +00009184
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009185 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00009186 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9187
9188 resType = ActiveExpr->getType();
9189 ValueDependent = ActiveExpr->isValueDependent();
9190 VK = ActiveExpr->getValueKind();
9191 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009192 }
9193
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009194 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00009195 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00009196 resType->isDependentType(),
9197 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00009198}
9199
Steve Naroffc540d662008-09-03 18:15:37 +00009200//===----------------------------------------------------------------------===//
9201// Clang Extensions.
9202//===----------------------------------------------------------------------===//
9203
9204/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00009205void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009206 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00009207 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009208 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00009209 if (CurScope)
9210 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009211 else
9212 CurContext = Block;
John McCallf1a3c2a2011-11-11 03:19:12 +00009213
Eli Friedman34b49062012-01-26 03:00:14 +00009214 getCurBlock()->HasImplicitReturnType = true;
9215
John McCallf1a3c2a2011-11-11 03:19:12 +00009216 // Enter a new evaluation context to insulate the block from any
9217 // cleanups from the enclosing full-expression.
9218 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009219}
9220
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009221void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9222 Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00009223 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00009224 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009225 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009226
John McCall8cb7bdf2010-06-04 23:28:52 +00009227 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00009228 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00009229
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009230 // FIXME: We should allow unexpanded parameter packs here, but that would,
9231 // in turn, make the block expression contain unexpanded parameter packs.
9232 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9233 // Drop the parameters.
9234 FunctionProtoType::ExtProtoInfo EPI;
9235 EPI.HasTrailingReturn = false;
9236 EPI.TypeQuals |= DeclSpec::TQ_const;
9237 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9238 EPI);
9239 Sig = Context.getTrivialTypeSourceInfo(T);
9240 }
9241
John McCall3882ace2011-01-05 12:14:39 +00009242 // GetTypeForDeclarator always produces a function type for a block
9243 // literal signature. Furthermore, it is always a FunctionProtoType
9244 // unless the function was written with a typedef.
9245 assert(T->isFunctionType() &&
9246 "GetTypeForDeclarator made a non-function block signature");
9247
9248 // Look for an explicit signature in that function type.
9249 FunctionProtoTypeLoc ExplicitSignature;
9250
9251 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9252 if (isa<FunctionProtoTypeLoc>(tmp)) {
9253 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9254
9255 // Check whether that explicit signature was synthesized by
9256 // GetTypeForDeclarator. If so, don't save that as part of the
9257 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00009258 if (ExplicitSignature.getLocalRangeBegin() ==
9259 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00009260 // This would be much cheaper if we stored TypeLocs instead of
9261 // TypeSourceInfos.
9262 TypeLoc Result = ExplicitSignature.getResultLoc();
9263 unsigned Size = Result.getFullDataSize();
9264 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9265 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9266
9267 ExplicitSignature = FunctionProtoTypeLoc();
9268 }
John McCalla3ccba02010-06-04 11:21:44 +00009269 }
Mike Stump11289f42009-09-09 15:08:12 +00009270
John McCall3882ace2011-01-05 12:14:39 +00009271 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9272 CurBlock->FunctionType = T;
9273
9274 const FunctionType *Fn = T->getAs<FunctionType>();
9275 QualType RetTy = Fn->getResultType();
9276 bool isVariadic =
9277 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9278
John McCall8e346702010-06-04 19:02:56 +00009279 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00009280
John McCalla3ccba02010-06-04 11:21:44 +00009281 // Don't allow returning a objc interface by value.
9282 if (RetTy->isObjCObjectType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009283 Diag(ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00009284 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9285 return;
9286 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009287
John McCalla3ccba02010-06-04 11:21:44 +00009288 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00009289 // return type. TODO: what should we do with declarators like:
9290 // ^ * { ... }
9291 // If the answer is "apply template argument deduction"....
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009292 if (RetTy != Context.DependentTy) {
John McCalla3ccba02010-06-04 11:21:44 +00009293 CurBlock->ReturnType = RetTy;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009294 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman34b49062012-01-26 03:00:14 +00009295 CurBlock->HasImplicitReturnType = false;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009296 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009297
John McCalla3ccba02010-06-04 11:21:44 +00009298 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009299 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00009300 if (ExplicitSignature) {
9301 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9302 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009303 if (Param->getIdentifier() == 0 &&
9304 !Param->isImplicit() &&
9305 !Param->isInvalidDecl() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009306 !getLangOpts().CPlusPlus)
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009307 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00009308 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009309 }
John McCalla3ccba02010-06-04 11:21:44 +00009310
9311 // Fake up parameter variables if we have a typedef, like
9312 // ^ fntype { ... }
9313 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9314 for (FunctionProtoType::arg_type_iterator
9315 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9316 ParmVarDecl *Param =
9317 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009318 ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00009319 *I);
John McCall8e346702010-06-04 19:02:56 +00009320 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009321 }
Steve Naroffc540d662008-09-03 18:15:37 +00009322 }
John McCalla3ccba02010-06-04 11:21:44 +00009323
John McCall8e346702010-06-04 19:02:56 +00009324 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009325 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00009326 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00009327 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9328 CurBlock->TheDecl->param_end(),
9329 /*CheckParameterNames=*/false);
9330 }
9331
John McCalla3ccba02010-06-04 11:21:44 +00009332 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009333 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009334
John McCalla3ccba02010-06-04 11:21:44 +00009335 // Put the parameter variables in scope. We can bail out immediately
9336 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009337 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009338 return;
9339
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009340 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009341 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9342 (*AI)->setOwningFunction(CurBlock->TheDecl);
9343
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009344 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009345 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009346 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009347
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009348 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009349 }
John McCallf7b2fb52010-01-22 00:28:27 +00009350 }
Steve Naroffc540d662008-09-03 18:15:37 +00009351}
9352
9353/// ActOnBlockError - If there is an error parsing a block, this callback
9354/// is invoked to pop the information about the block from the action impl.
9355void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCallf1a3c2a2011-11-11 03:19:12 +00009356 // Leave the expression-evaluation context.
9357 DiscardCleanupsInEvaluationContext();
9358 PopExpressionEvaluationContext();
9359
Steve Naroffc540d662008-09-03 18:15:37 +00009360 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009361 PopDeclContext();
Eli Friedman71c80552012-01-05 03:35:19 +00009362 PopFunctionScopeInfo();
Steve Naroffc540d662008-09-03 18:15:37 +00009363}
9364
9365/// ActOnBlockStmtExpr - This is called when the body of a block statement
9366/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009367ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009368 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009369 // If blocks are disabled, emit an error.
9370 if (!LangOpts.Blocks)
9371 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009372
John McCallf1a3c2a2011-11-11 03:19:12 +00009373 // Leave the expression-evaluation context.
John McCall85110b42012-03-08 22:00:17 +00009374 if (hasAnyUnrecoverableErrorsInThisFunction())
9375 DiscardCleanupsInEvaluationContext();
John McCallf1a3c2a2011-11-11 03:19:12 +00009376 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9377 PopExpressionEvaluationContext();
9378
Douglas Gregor9a28e842010-03-01 23:15:13 +00009379 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rosed39e5f12012-07-02 21:19:23 +00009380
9381 if (BSI->HasImplicitReturnType)
9382 deduceClosureReturnType(*BSI);
9383
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009384 PopDeclContext();
9385
Steve Naroffc540d662008-09-03 18:15:37 +00009386 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009387 if (!BSI->ReturnType.isNull())
9388 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009389
Mike Stump3bf1ab42009-07-28 22:04:01 +00009390 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009391 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009392
John McCallc63de662011-02-02 13:00:07 +00009393 // Set the captured variables on the block.
Eli Friedman20139d32012-01-11 02:36:31 +00009394 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9395 SmallVector<BlockDecl::Capture, 4> Captures;
9396 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9397 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9398 if (Cap.isThisCapture())
9399 continue;
Eli Friedman24af8502012-02-03 22:47:37 +00009400 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedman20139d32012-01-11 02:36:31 +00009401 Cap.isNested(), Cap.getCopyExpr());
9402 Captures.push_back(NewCap);
9403 }
9404 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9405 BSI->CXXThisCaptureIndex != 0);
John McCallc63de662011-02-02 13:00:07 +00009406
John McCall8e346702010-06-04 19:02:56 +00009407 // If the user wrote a function type in some form, try to use that.
9408 if (!BSI->FunctionType.isNull()) {
9409 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9410
9411 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9412 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9413
9414 // Turn protoless block types into nullary block types.
9415 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009416 FunctionProtoType::ExtProtoInfo EPI;
9417 EPI.ExtInfo = Ext;
9418 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009419
9420 // Otherwise, if we don't need to change anything about the function type,
9421 // preserve its sugar structure.
9422 } else if (FTy->getResultType() == RetTy &&
9423 (!NoReturn || FTy->getNoReturnAttr())) {
9424 BlockTy = BSI->FunctionType;
9425
9426 // Otherwise, make the minimal modifications to the function type.
9427 } else {
9428 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009429 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9430 EPI.TypeQuals = 0; // FIXME: silently?
9431 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009432 BlockTy = Context.getFunctionType(RetTy,
9433 FPT->arg_type_begin(),
9434 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009435 EPI);
John McCall8e346702010-06-04 19:02:56 +00009436 }
9437
9438 // If we don't have a function type, just build one from nothing.
9439 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009440 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00009441 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00009442 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009443 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009444
John McCall8e346702010-06-04 19:02:56 +00009445 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9446 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009447 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009448
Chris Lattner45542ea2009-04-19 05:28:12 +00009449 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00009450 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +00009451 !hasAnyUnrecoverableErrorsInThisFunction() &&
9452 !PP.isCodeCompletionEnabled())
John McCallb268a282010-08-23 23:25:46 +00009453 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009454
Chris Lattner60f84492011-02-17 23:58:47 +00009455 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009456
Jordan Rosed39e5f12012-07-02 21:19:23 +00009457 // Try to apply the named return value optimization. We have to check again
9458 // if we can do this, though, because blocks keep return statements around
9459 // to deduce an implicit return type.
9460 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9461 !BSI->TheDecl->isDependentContext())
9462 computeNRVO(Body, getCurBlock());
Douglas Gregor49695f02011-09-06 20:46:03 +00009463
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009464 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9465 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedman71c80552012-01-05 03:35:19 +00009466 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009467
John McCall28fc7092011-11-10 05:35:25 +00009468 // If the block isn't obviously global, i.e. it captures anything at
John McCalld2393872012-04-13 01:08:17 +00009469 // all, then we need to do a few things in the surrounding context:
John McCall28fc7092011-11-10 05:35:25 +00009470 if (Result->getBlockDecl()->hasCaptures()) {
John McCalld2393872012-04-13 01:08:17 +00009471 // First, this expression has a new cleanup object.
John McCall28fc7092011-11-10 05:35:25 +00009472 ExprCleanupObjects.push_back(Result->getBlockDecl());
9473 ExprNeedsCleanups = true;
John McCalld2393872012-04-13 01:08:17 +00009474
9475 // It also gets a branch-protected scope if any of the captured
9476 // variables needs destruction.
9477 for (BlockDecl::capture_const_iterator
9478 ci = Result->getBlockDecl()->capture_begin(),
9479 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9480 const VarDecl *var = ci->getVariable();
9481 if (var->getType().isDestructedType() != QualType::DK_none) {
9482 getCurFunction()->setHasBranchProtectedScope();
9483 break;
9484 }
9485 }
John McCall28fc7092011-11-10 05:35:25 +00009486 }
Fariborz Jahanian197c68c2012-03-06 18:41:35 +00009487
Douglas Gregor9a28e842010-03-01 23:15:13 +00009488 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009489}
9490
John McCalldadc5752010-08-24 06:29:42 +00009491ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009492 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009493 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009494 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009495 GetTypeFromParser(Ty, &TInfo);
9496 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009497}
9498
John McCalldadc5752010-08-24 06:29:42 +00009499ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009500 Expr *E, TypeSourceInfo *TInfo,
9501 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009502 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009503
Eli Friedman121ba0c2008-08-09 23:32:40 +00009504 // Get the va_list type
9505 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009506 if (VaListType->isArrayType()) {
9507 // Deal with implicit array decay; for example, on x86-64,
9508 // va_list is an array, but it's supposed to decay to
9509 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009510 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009511 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009512 ExprResult Result = UsualUnaryConversions(E);
9513 if (Result.isInvalid())
9514 return ExprError();
9515 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00009516 } else {
9517 // Otherwise, the va_list argument must be an l-value because
9518 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009519 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009520 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009521 return ExprError();
9522 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009523
Douglas Gregorad3150c2009-05-19 23:10:31 +00009524 if (!E->isTypeDependent() &&
9525 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009526 return ExprError(Diag(E->getLocStart(),
9527 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009528 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009529 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009530
David Majnemerc75d1a12011-06-14 05:17:32 +00009531 if (!TInfo->getType()->isDependentType()) {
9532 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009533 diag::err_second_parameter_to_va_arg_incomplete,
9534 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009535 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00009536
David Majnemerc75d1a12011-06-14 05:17:32 +00009537 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregorae298422012-05-04 17:09:59 +00009538 TInfo->getType(),
9539 diag::err_second_parameter_to_va_arg_abstract,
9540 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009541 return ExprError();
9542
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009543 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00009544 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009545 TInfo->getType()->isObjCLifetimeType()
9546 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9547 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00009548 << TInfo->getType()
9549 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009550 }
Eli Friedman6290ae42011-07-11 21:45:59 +00009551
9552 // Check for va_arg where arguments of the given type will be promoted
9553 // (i.e. this va_arg is guaranteed to have undefined behavior).
9554 QualType PromoteType;
9555 if (TInfo->getType()->isPromotableIntegerType()) {
9556 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9557 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9558 PromoteType = QualType();
9559 }
9560 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9561 PromoteType = Context.DoubleTy;
9562 if (!PromoteType.isNull())
9563 Diag(TInfo->getTypeLoc().getBeginLoc(),
9564 diag::warn_second_parameter_to_va_arg_never_compatible)
9565 << TInfo->getType()
9566 << PromoteType
9567 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00009568 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009569
Abramo Bagnara27db2392010-08-10 10:06:15 +00009570 QualType T = TInfo->getType().getNonLValueExprType(Context);
9571 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009572}
9573
John McCalldadc5752010-08-24 06:29:42 +00009574ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009575 // The type of __null will be int or long, depending on the size of
9576 // pointers on the target.
9577 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009578 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9579 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009580 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009581 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009582 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009583 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009584 Ty = Context.LongLongTy;
9585 else {
David Blaikie83d382b2011-09-23 05:06:16 +00009586 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009587 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009588
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009589 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009590}
9591
Alexis Huntc46382e2010-04-28 23:02:27 +00009592static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009593 Expr *SrcExpr, FixItHint &Hint) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009594 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonace5d072009-11-10 04:46:30 +00009595 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009596
Anders Carlssonace5d072009-11-10 04:46:30 +00009597 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9598 if (!PT)
9599 return;
9600
9601 // Check if the destination is of type 'id'.
9602 if (!PT->isObjCIdType()) {
9603 // Check if the destination is the 'NSString' interface.
9604 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9605 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9606 return;
9607 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009608
John McCallfe96e0b2011-11-06 09:01:30 +00009609 // Ignore any parens, implicit casts (should only be
9610 // array-to-pointer decays), and not-so-opaque values. The last is
9611 // important for making this trigger for property assignments.
9612 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9613 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9614 if (OV->getSourceExpr())
9615 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9616
9617 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregorfb65e592011-07-27 05:40:30 +00009618 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00009619 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009620
Douglas Gregora771f462010-03-31 17:46:05 +00009621 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009622}
9623
Chris Lattner9bad62c2008-01-04 18:04:52 +00009624bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9625 SourceLocation Loc,
9626 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009627 Expr *SrcExpr, AssignmentAction Action,
9628 bool *Complained) {
9629 if (Complained)
9630 *Complained = false;
9631
Chris Lattner9bad62c2008-01-04 18:04:52 +00009632 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00009633 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009634 bool isInvalid = false;
Eli Friedman381f4312012-02-29 20:59:56 +00009635 unsigned DiagKind = 0;
Douglas Gregora771f462010-03-31 17:46:05 +00009636 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00009637 ConversionFixItGenerator ConvHints;
9638 bool MayHaveConvFixit = false;
Richard Trieucaff2472011-11-23 22:32:32 +00009639 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009640
Chris Lattner9bad62c2008-01-04 18:04:52 +00009641 switch (ConvTy) {
Fariborz Jahanian268fec12012-07-17 18:00:08 +00009642 case Compatible:
9643 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9644 return false;
9645
Chris Lattner940cfeb2008-01-04 18:22:42 +00009646 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009647 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00009648 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9649 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009650 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009651 case IntToPointer:
9652 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009653 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9654 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009655 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009656 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009657 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009658 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009659 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9660 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009661 if (Hint.isNull() && !CheckInferredResultType) {
9662 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9663 }
9664 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009665 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009666 case IncompatiblePointerSign:
9667 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9668 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009669 case FunctionVoidPointer:
9670 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9671 break;
John McCall4fff8f62011-02-01 00:10:29 +00009672 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009673 // Perform array-to-pointer decay if necessary.
9674 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9675
John McCall4fff8f62011-02-01 00:10:29 +00009676 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9677 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9678 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9679 DiagKind = diag::err_typecheck_incompatible_address_space;
9680 break;
John McCall31168b02011-06-15 23:02:42 +00009681
9682
9683 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009684 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009685 break;
John McCall4fff8f62011-02-01 00:10:29 +00009686 }
9687
9688 llvm_unreachable("unknown error case for discarding qualifiers!");
9689 // fallthrough
9690 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009691 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009692 // If the qualifiers lost were because we were applying the
9693 // (deprecated) C++ conversion from a string literal to a char*
9694 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9695 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009696 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009697 // bit of refactoring (so that the second argument is an
9698 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009699 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009700 // C++ semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009701 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009702 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9703 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009704 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9705 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009706 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009707 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009708 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009709 case IntToBlockPointer:
9710 DiagKind = diag::err_int_to_block_pointer;
9711 break;
9712 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009713 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009714 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009715 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009716 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009717 // it can give a more specific diagnostic.
9718 DiagKind = diag::warn_incompatible_qualified_id;
9719 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009720 case IncompatibleVectors:
9721 DiagKind = diag::warn_incompatible_vectors;
9722 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009723 case IncompatibleObjCWeakRef:
9724 DiagKind = diag::err_arc_weak_unavailable_assign;
9725 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009726 case Incompatible:
9727 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009728 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9729 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009730 isInvalid = true;
Richard Trieucaff2472011-11-23 22:32:32 +00009731 MayHaveFunctionDiff = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009732 break;
9733 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009734
Douglas Gregorc68e1402010-04-09 00:35:39 +00009735 QualType FirstType, SecondType;
9736 switch (Action) {
9737 case AA_Assigning:
9738 case AA_Initializing:
9739 // The destination type comes first.
9740 FirstType = DstType;
9741 SecondType = SrcType;
9742 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009743
Douglas Gregorc68e1402010-04-09 00:35:39 +00009744 case AA_Returning:
9745 case AA_Passing:
9746 case AA_Converting:
9747 case AA_Sending:
9748 case AA_Casting:
9749 // The source type comes first.
9750 FirstType = SrcType;
9751 SecondType = DstType;
9752 break;
9753 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009754
Anna Zaks3b402712011-07-28 19:51:27 +00009755 PartialDiagnostic FDiag = PDiag(DiagKind);
9756 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9757
9758 // If we can fix the conversion, suggest the FixIts.
9759 assert(ConvHints.isNull() || Hint.isNull());
9760 if (!ConvHints.isNull()) {
Benjamin Kramer490afa62012-01-14 21:05:10 +00009761 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9762 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks3b402712011-07-28 19:51:27 +00009763 FDiag << *HI;
9764 } else {
9765 FDiag << Hint;
9766 }
9767 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9768
Richard Trieucaff2472011-11-23 22:32:32 +00009769 if (MayHaveFunctionDiff)
9770 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9771
Anna Zaks3b402712011-07-28 19:51:27 +00009772 Diag(Loc, FDiag);
9773
Richard Trieucaff2472011-11-23 22:32:32 +00009774 if (SecondType == Context.OverloadTy)
9775 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9776 FirstType);
9777
Douglas Gregor33823722011-06-11 01:09:30 +00009778 if (CheckInferredResultType)
9779 EmitRelatedResultTypeNote(SrcExpr);
9780
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009781 if (Complained)
9782 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009783 return isInvalid;
9784}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009785
Richard Smithf4c51d92012-02-04 09:53:13 +00009786ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9787 llvm::APSInt *Result) {
Douglas Gregore2b37442012-05-04 22:38:52 +00009788 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9789 public:
9790 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9791 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9792 }
9793 } Diagnoser;
9794
9795 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9796}
9797
9798ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9799 llvm::APSInt *Result,
9800 unsigned DiagID,
9801 bool AllowFold) {
9802 class IDDiagnoser : public VerifyICEDiagnoser {
9803 unsigned DiagID;
9804
9805 public:
9806 IDDiagnoser(unsigned DiagID)
9807 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9808
9809 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9810 S.Diag(Loc, DiagID) << SR;
9811 }
9812 } Diagnoser(DiagID);
9813
9814 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9815}
9816
9817void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9818 SourceRange SR) {
9819 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smithf4c51d92012-02-04 09:53:13 +00009820}
9821
Benjamin Kramer33adaae2012-04-18 14:22:41 +00009822ExprResult
9823Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregore2b37442012-05-04 22:38:52 +00009824 VerifyICEDiagnoser &Diagnoser,
9825 bool AllowFold) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009826 SourceLocation DiagLoc = E->getLocStart();
Richard Smithf4c51d92012-02-04 09:53:13 +00009827
David Blaikiebbafb8a2012-03-11 07:00:24 +00009828 if (getLangOpts().CPlusPlus0x) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009829 // C++11 [expr.const]p5:
9830 // If an expression of literal class type is used in a context where an
9831 // integral constant expression is required, then that class type shall
9832 // have a single non-explicit conversion function to an integral or
9833 // unscoped enumeration type
9834 ExprResult Converted;
Douglas Gregore2b37442012-05-04 22:38:52 +00009835 if (!Diagnoser.Suppress) {
9836 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9837 public:
9838 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9839
9840 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9841 QualType T) {
9842 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9843 }
9844
9845 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9846 SourceLocation Loc,
9847 QualType T) {
9848 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9849 }
9850
9851 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9852 SourceLocation Loc,
9853 QualType T,
9854 QualType ConvTy) {
9855 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9856 }
9857
9858 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9859 CXXConversionDecl *Conv,
9860 QualType ConvTy) {
9861 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9862 << ConvTy->isEnumeralType() << ConvTy;
9863 }
9864
9865 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9866 QualType T) {
9867 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9868 }
9869
9870 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9871 CXXConversionDecl *Conv,
9872 QualType ConvTy) {
9873 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9874 << ConvTy->isEnumeralType() << ConvTy;
9875 }
9876
9877 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9878 SourceLocation Loc,
9879 QualType T,
9880 QualType ConvTy) {
9881 return DiagnosticBuilder::getEmpty();
9882 }
9883 } ConvertDiagnoser;
9884
9885 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9886 ConvertDiagnoser,
9887 /*AllowScopedEnumerations*/ false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009888 } else {
9889 // The caller wants to silently enquire whether this is an ICE. Don't
9890 // produce any diagnostics if it isn't.
Douglas Gregore2b37442012-05-04 22:38:52 +00009891 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
9892 public:
9893 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
9894
9895 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9896 QualType T) {
9897 return DiagnosticBuilder::getEmpty();
9898 }
9899
9900 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9901 SourceLocation Loc,
9902 QualType T) {
9903 return DiagnosticBuilder::getEmpty();
9904 }
9905
9906 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9907 SourceLocation Loc,
9908 QualType T,
9909 QualType ConvTy) {
9910 return DiagnosticBuilder::getEmpty();
9911 }
9912
9913 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9914 CXXConversionDecl *Conv,
9915 QualType ConvTy) {
9916 return DiagnosticBuilder::getEmpty();
9917 }
9918
9919 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9920 QualType T) {
9921 return DiagnosticBuilder::getEmpty();
9922 }
9923
9924 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9925 CXXConversionDecl *Conv,
9926 QualType ConvTy) {
9927 return DiagnosticBuilder::getEmpty();
9928 }
9929
9930 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9931 SourceLocation Loc,
9932 QualType T,
9933 QualType ConvTy) {
9934 return DiagnosticBuilder::getEmpty();
9935 }
9936 } ConvertDiagnoser;
9937
9938 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9939 ConvertDiagnoser, false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009940 }
9941 if (Converted.isInvalid())
9942 return Converted;
9943 E = Converted.take();
9944 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9945 return ExprError();
9946 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9947 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregore2b37442012-05-04 22:38:52 +00009948 if (!Diagnoser.Suppress)
9949 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithf4c51d92012-02-04 09:53:13 +00009950 return ExprError();
9951 }
9952
Richard Smith902ca212011-12-14 23:32:26 +00009953 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
9954 // in the non-ICE case.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009955 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009956 if (Result)
9957 *Result = E->EvaluateKnownConstInt(Context);
9958 return Owned(E);
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009959 }
9960
Anders Carlssone54e8a12008-11-30 19:50:32 +00009961 Expr::EvalResult EvalResult;
Richard Smith92b1ce02011-12-12 09:28:41 +00009962 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
9963 EvalResult.Diag = &Notes;
Anders Carlssone54e8a12008-11-30 19:50:32 +00009964
Richard Smith902ca212011-12-14 23:32:26 +00009965 // Try to evaluate the expression, and produce diagnostics explaining why it's
9966 // not a constant expression as a side-effect.
9967 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
9968 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
9969
9970 // In C++11, we can rely on diagnostics being produced for any expression
9971 // which is not a constant expression. If no diagnostics were produced, then
9972 // this is a constant expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009973 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smith902ca212011-12-14 23:32:26 +00009974 if (Result)
9975 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +00009976 return Owned(E);
9977 }
9978
9979 // If our only note is the usual "invalid subexpression" note, just point
9980 // the caret at its location rather than producing an essentially
9981 // redundant note.
9982 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9983 diag::note_invalid_subexpr_in_const_expr) {
9984 DiagLoc = Notes[0].first;
9985 Notes.clear();
Richard Smith902ca212011-12-14 23:32:26 +00009986 }
9987
9988 if (!Folded || !AllowFold) {
Douglas Gregore2b37442012-05-04 22:38:52 +00009989 if (!Diagnoser.Suppress) {
9990 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith92b1ce02011-12-12 09:28:41 +00009991 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9992 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone54e8a12008-11-30 19:50:32 +00009993 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009994
Richard Smithf4c51d92012-02-04 09:53:13 +00009995 return ExprError();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009996 }
9997
Douglas Gregore2b37442012-05-04 22:38:52 +00009998 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith2ec40612012-01-15 03:51:30 +00009999 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10000 Diag(Notes[I].first, Notes[I].second);
Mike Stump4e1f26a2009-02-19 03:04:26 +000010001
Anders Carlssone54e8a12008-11-30 19:50:32 +000010002 if (Result)
10003 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +000010004 return Owned(E);
Anders Carlssone54e8a12008-11-30 19:50:32 +000010005}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010006
Eli Friedman456f0182012-01-20 01:26:23 +000010007namespace {
10008 // Handle the case where we conclude a expression which we speculatively
10009 // considered to be unevaluated is actually evaluated.
10010 class TransformToPE : public TreeTransform<TransformToPE> {
10011 typedef TreeTransform<TransformToPE> BaseTransform;
10012
10013 public:
10014 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10015
10016 // Make sure we redo semantic analysis
10017 bool AlwaysRebuild() { return true; }
10018
Eli Friedman5f0ca242012-02-06 23:29:57 +000010019 // Make sure we handle LabelStmts correctly.
10020 // FIXME: This does the right thing, but maybe we need a more general
10021 // fix to TreeTransform?
10022 StmtResult TransformLabelStmt(LabelStmt *S) {
10023 S->getDecl()->setStmt(0);
10024 return BaseTransform::TransformLabelStmt(S);
10025 }
10026
Eli Friedman456f0182012-01-20 01:26:23 +000010027 // We need to special-case DeclRefExprs referring to FieldDecls which
10028 // are not part of a member pointer formation; normal TreeTransforming
10029 // doesn't catch this case because of the way we represent them in the AST.
10030 // FIXME: This is a bit ugly; is it really the best way to handle this
10031 // case?
10032 //
10033 // Error on DeclRefExprs referring to FieldDecls.
10034 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10035 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie131fcb42012-08-06 22:47:24 +000010036 !SemaRef.isUnevaluatedContext())
Eli Friedman456f0182012-01-20 01:26:23 +000010037 return SemaRef.Diag(E->getLocation(),
10038 diag::err_invalid_non_static_member_use)
10039 << E->getDecl() << E->getSourceRange();
10040
10041 return BaseTransform::TransformDeclRefExpr(E);
10042 }
10043
10044 // Exception: filter out member pointer formation
10045 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10046 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10047 return E;
10048
10049 return BaseTransform::TransformUnaryOperator(E);
10050 }
10051
Douglas Gregor89625492012-02-09 08:14:43 +000010052 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10053 // Lambdas never need to be transformed.
10054 return E;
10055 }
Eli Friedman456f0182012-01-20 01:26:23 +000010056 };
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000010057}
10058
Eli Friedman456f0182012-01-20 01:26:23 +000010059ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedmane4f22df2012-02-29 04:03:55 +000010060 assert(ExprEvalContexts.back().Context == Unevaluated &&
10061 "Should only transform unevaluated expressions");
Eli Friedman456f0182012-01-20 01:26:23 +000010062 ExprEvalContexts.back().Context =
10063 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10064 if (ExprEvalContexts.back().Context == Unevaluated)
10065 return E;
10066 return TransformToPE(*this).TransformExpr(E);
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000010067}
10068
Douglas Gregorff790f12009-11-26 00:44:06 +000010069void
Douglas Gregor7fcbd902012-02-21 00:37:24 +000010070Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smithfd555f62012-02-22 02:04:18 +000010071 Decl *LambdaContextDecl,
10072 bool IsDecltype) {
Douglas Gregorff790f12009-11-26 00:44:06 +000010073 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +000010074 ExpressionEvaluationContextRecord(NewContext,
John McCall28fc7092011-11-10 05:35:25 +000010075 ExprCleanupObjects.size(),
Douglas Gregor7fcbd902012-02-21 00:37:24 +000010076 ExprNeedsCleanups,
Richard Smithfd555f62012-02-22 02:04:18 +000010077 LambdaContextDecl,
10078 IsDecltype));
John McCall31168b02011-06-15 23:02:42 +000010079 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010080 if (!MaybeODRUseExprs.empty())
10081 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010082}
10083
Richard Trieucfc491d2011-08-02 04:35:43 +000010084void Sema::PopExpressionEvaluationContext() {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010085 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010086
Douglas Gregor89625492012-02-09 08:14:43 +000010087 if (!Rec.Lambdas.empty()) {
10088 if (Rec.Context == Unevaluated) {
10089 // C++11 [expr.prim.lambda]p2:
10090 // A lambda-expression shall not appear in an unevaluated operand
10091 // (Clause 5).
10092 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10093 Diag(Rec.Lambdas[I]->getLocStart(),
10094 diag::err_lambda_unevaluated_operand);
10095 } else {
10096 // Mark the capture expressions odr-used. This was deferred
10097 // during lambda expression creation.
10098 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10099 LambdaExpr *Lambda = Rec.Lambdas[I];
10100 for (LambdaExpr::capture_init_iterator
10101 C = Lambda->capture_init_begin(),
10102 CEnd = Lambda->capture_init_end();
10103 C != CEnd; ++C) {
10104 MarkDeclarationsReferencedInExpr(*C);
10105 }
10106 }
10107 }
10108 }
10109
Douglas Gregorff790f12009-11-26 00:44:06 +000010110 // When are coming out of an unevaluated context, clear out any
10111 // temporaries that we may have created as part of the evaluation of
10112 // the expression in that context: they aren't relevant because they
10113 // will never be constructed.
Richard Smith764d2fe2011-12-20 02:08:33 +000010114 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall28fc7092011-11-10 05:35:25 +000010115 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10116 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000010117 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010118 CleanupVarDeclMarking();
10119 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCall31168b02011-06-15 23:02:42 +000010120 // Otherwise, merge the contexts together.
10121 } else {
10122 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010123 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10124 Rec.SavedMaybeODRUseExprs.end());
John McCall31168b02011-06-15 23:02:42 +000010125 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010126
10127 // Pop the current expression evaluation context off the stack.
10128 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010129}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010130
John McCall31168b02011-06-15 23:02:42 +000010131void Sema::DiscardCleanupsInEvaluationContext() {
John McCall28fc7092011-11-10 05:35:25 +000010132 ExprCleanupObjects.erase(
10133 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10134 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000010135 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010136 MaybeODRUseExprs.clear();
John McCall31168b02011-06-15 23:02:42 +000010137}
10138
Eli Friedmane0afc982012-01-21 01:01:51 +000010139ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10140 if (!E->getType()->isVariablyModifiedType())
10141 return E;
10142 return TranformToPotentiallyEvaluated(E);
10143}
10144
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +000010145static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010146 // Do not mark anything as "used" within a dependent context; wait for
10147 // an instantiation.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010148 if (SemaRef.CurContext->isDependentContext())
10149 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010150
Eli Friedmanfa0df832012-02-02 03:46:19 +000010151 switch (SemaRef.ExprEvalContexts.back().Context) {
10152 case Sema::Unevaluated:
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010153 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman02b58512012-01-21 04:44:06 +000010154 // (Depending on how you read the standard, we actually do need to do
10155 // something here for null pointer constants, but the standard's
10156 // definition of a null pointer constant is completely crazy.)
Eli Friedmanfa0df832012-02-02 03:46:19 +000010157 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010158
Eli Friedmanfa0df832012-02-02 03:46:19 +000010159 case Sema::ConstantEvaluated:
10160 case Sema::PotentiallyEvaluated:
Eli Friedman02b58512012-01-21 04:44:06 +000010161 // We are in a potentially evaluated expression (or a constant-expression
10162 // in C++03); we need to do implicit template instantiation, implicitly
10163 // define class members, and mark most declarations as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010164 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010165
Eli Friedmanfa0df832012-02-02 03:46:19 +000010166 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010167 // Referenced declarations will only be used if the construct in the
10168 // containing expression is used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010169 return false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010170 }
Matt Beaumont-Gay248bc722012-02-02 18:35:35 +000010171 llvm_unreachable("Invalid context");
Eli Friedmanfa0df832012-02-02 03:46:19 +000010172}
10173
10174/// \brief Mark a function referenced, and check whether it is odr-used
10175/// (C++ [basic.def.odr]p2, C99 6.9p3)
10176void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10177 assert(Func && "No function?");
10178
10179 Func->setReferenced();
10180
Richard Smith4a941e22012-02-14 22:25:15 +000010181 // Don't mark this function as used multiple times, unless it's a constexpr
10182 // function which we need to instantiate.
10183 if (Func->isUsed(false) &&
10184 !(Func->isConstexpr() && !Func->getBody() &&
10185 Func->isImplicitlyInstantiable()))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010186 return;
10187
10188 if (!IsPotentiallyEvaluatedContext(*this))
10189 return;
Mike Stump11289f42009-09-09 15:08:12 +000010190
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010191 // Note that this declaration has been used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010192 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010193 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010194 if (Constructor->isDefaultConstructor()) {
10195 if (Constructor->isTrivial())
10196 return;
10197 if (!Constructor->isUsed(false))
10198 DefineImplicitDefaultConstructor(Loc, Constructor);
10199 } else if (Constructor->isCopyConstructor()) {
10200 if (!Constructor->isUsed(false))
10201 DefineImplicitCopyConstructor(Loc, Constructor);
10202 } else if (Constructor->isMoveConstructor()) {
10203 if (!Constructor->isUsed(false))
10204 DefineImplicitMoveConstructor(Loc, Constructor);
10205 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010206 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010207
Douglas Gregor88d292c2010-05-13 16:44:06 +000010208 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010209 } else if (CXXDestructorDecl *Destructor =
10210 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010211 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10212 !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010213 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010214 if (Destructor->isVirtual())
10215 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010216 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010217 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10218 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010219 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010220 if (!MethodDecl->isUsed(false)) {
10221 if (MethodDecl->isCopyAssignmentOperator())
10222 DefineImplicitCopyAssignment(Loc, MethodDecl);
10223 else
10224 DefineImplicitMoveAssignment(Loc, MethodDecl);
10225 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010226 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10227 MethodDecl->getParent()->isLambda()) {
10228 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10229 if (Conversion->isLambdaToBlockPointerConversion())
10230 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10231 else
10232 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010233 } else if (MethodDecl->isVirtual())
10234 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010235 }
John McCall83779672011-02-19 02:53:41 +000010236
Eli Friedmanfa0df832012-02-02 03:46:19 +000010237 // Recursive functions should be marked when used from another function.
10238 // FIXME: Is this really right?
10239 if (CurContext == Func) return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010240
Richard Smithd3b5c9082012-07-27 04:22:15 +000010241 // Resolve the exception specification for any function which is
Richard Smithf623c962012-04-17 00:58:00 +000010242 // used: CodeGen will need it.
Richard Smithd3729422012-04-19 00:08:28 +000010243 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010244 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10245 ResolveExceptionSpec(Loc, FPT);
Richard Smithf623c962012-04-17 00:58:00 +000010246
Eli Friedmanfa0df832012-02-02 03:46:19 +000010247 // Implicit instantiation of function templates and member functions of
10248 // class templates.
10249 if (Func->isImplicitlyInstantiable()) {
10250 bool AlreadyInstantiated = false;
Richard Smith4a941e22012-02-14 22:25:15 +000010251 SourceLocation PointOfInstantiation = Loc;
Eli Friedmanfa0df832012-02-02 03:46:19 +000010252 if (FunctionTemplateSpecializationInfo *SpecInfo
10253 = Func->getTemplateSpecializationInfo()) {
10254 if (SpecInfo->getPointOfInstantiation().isInvalid())
10255 SpecInfo->setPointOfInstantiation(Loc);
10256 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010257 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010258 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010259 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10260 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010261 } else if (MemberSpecializationInfo *MSInfo
10262 = Func->getMemberSpecializationInfo()) {
10263 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregor06db9f52009-10-12 20:18:28 +000010264 MSInfo->setPointOfInstantiation(Loc);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010265 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010266 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010267 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010268 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10269 }
Douglas Gregor06db9f52009-10-12 20:18:28 +000010270 }
Mike Stump11289f42009-09-09 15:08:12 +000010271
Richard Smith4a941e22012-02-14 22:25:15 +000010272 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010273 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10274 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith4a941e22012-02-14 22:25:15 +000010275 PendingLocalImplicitInstantiations.push_back(
10276 std::make_pair(Func, PointOfInstantiation));
10277 else if (Func->isConstexpr())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010278 // Do not defer instantiations of constexpr functions, to avoid the
10279 // expression evaluator needing to call back into Sema if it sees a
10280 // call to such a function.
Richard Smith4a941e22012-02-14 22:25:15 +000010281 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000010282 else {
Richard Smith4a941e22012-02-14 22:25:15 +000010283 PendingInstantiations.push_back(std::make_pair(Func,
10284 PointOfInstantiation));
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000010285 // Notify the consumer that a function was implicitly instantiated.
10286 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10287 }
John McCall83779672011-02-19 02:53:41 +000010288 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010289 } else {
10290 // Walk redefinitions, as some of them may be instantiable.
10291 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10292 e(Func->redecls_end()); i != e; ++i) {
10293 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10294 MarkFunctionReferenced(Loc, *i);
10295 }
Sam Weinigbae69142009-09-11 03:29:30 +000010296 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010297
10298 // Keep track of used but undefined functions.
10299 if (!Func->isPure() && !Func->hasBody() &&
10300 Func->getLinkage() != ExternalLinkage) {
10301 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10302 if (old.isInvalid()) old = Loc;
10303 }
10304
10305 Func->setUsed(true);
10306}
10307
Eli Friedman9bb33f52012-02-03 02:04:35 +000010308static void
10309diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10310 VarDecl *var, DeclContext *DC) {
Eli Friedmandd053f62012-02-07 00:15:00 +000010311 DeclContext *VarDC = var->getDeclContext();
10312
Eli Friedman9bb33f52012-02-03 02:04:35 +000010313 // If the parameter still belongs to the translation unit, then
10314 // we're actually just using one parameter in the declaration of
10315 // the next.
10316 if (isa<ParmVarDecl>(var) &&
Eli Friedmandd053f62012-02-07 00:15:00 +000010317 isa<TranslationUnitDecl>(VarDC))
Eli Friedman9bb33f52012-02-03 02:04:35 +000010318 return;
10319
Eli Friedmandd053f62012-02-07 00:15:00 +000010320 // For C code, don't diagnose about capture if we're not actually in code
10321 // right now; it's impossible to write a non-constant expression outside of
10322 // function context, so we'll get other (more useful) diagnostics later.
10323 //
10324 // For C++, things get a bit more nasty... it would be nice to suppress this
10325 // diagnostic for certain cases like using a local variable in an array bound
10326 // for a member of a local class, but the correct predicate is not obvious.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010327 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman9bb33f52012-02-03 02:04:35 +000010328 return;
10329
Eli Friedmandd053f62012-02-07 00:15:00 +000010330 if (isa<CXXMethodDecl>(VarDC) &&
10331 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10332 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10333 << var->getIdentifier();
10334 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10335 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10336 << var->getIdentifier() << fn->getDeclName();
10337 } else if (isa<BlockDecl>(VarDC)) {
10338 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10339 << var->getIdentifier();
10340 } else {
10341 // FIXME: Is there any other context where a local variable can be
10342 // declared?
10343 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10344 << var->getIdentifier();
10345 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010346
Eli Friedman9bb33f52012-02-03 02:04:35 +000010347 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10348 << var->getIdentifier();
Eli Friedmandd053f62012-02-07 00:15:00 +000010349
10350 // FIXME: Add additional diagnostic info about class etc. which prevents
10351 // capture.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010352}
10353
Douglas Gregor81495f32012-02-12 18:42:33 +000010354/// \brief Capture the given variable in the given lambda expression.
10355static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010356 VarDecl *Var, QualType FieldType,
10357 QualType DeclRefType,
Douglas Gregora8182f92012-05-16 17:01:33 +000010358 SourceLocation Loc,
10359 bool RefersToEnclosingLocal) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010360 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregor81495f32012-02-12 18:42:33 +000010361
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010362 // Build the non-static data member.
10363 FieldDecl *Field
10364 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10365 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smith2b013182012-06-10 03:12:00 +000010366 0, false, ICIS_NoInit);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010367 Field->setImplicit(true);
10368 Field->setAccess(AS_private);
Douglas Gregor3d23f7882012-02-09 02:12:34 +000010369 Lambda->addDecl(Field);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010370
10371 // C++11 [expr.prim.lambda]p21:
10372 // When the lambda-expression is evaluated, the entities that
10373 // are captured by copy are used to direct-initialize each
10374 // corresponding non-static data member of the resulting closure
10375 // object. (For array members, the array elements are
10376 // direct-initialized in increasing subscript order.) These
10377 // initializations are performed in the (unspecified) order in
10378 // which the non-static data members are declared.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010379
Douglas Gregor89625492012-02-09 08:14:43 +000010380 // Introduce a new evaluation context for the initialization, so
10381 // that temporaries introduced as part of the capture are retained
10382 // to be re-"exported" from the lambda expression itself.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010383 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10384
Douglas Gregorf02455e2012-02-10 09:26:04 +000010385 // C++ [expr.prim.labda]p12:
10386 // An entity captured by a lambda-expression is odr-used (3.2) in
10387 // the scope containing the lambda-expression.
Douglas Gregora8182f92012-05-16 17:01:33 +000010388 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10389 DeclRefType, VK_LValue, Loc);
Eli Friedman23b1be92012-03-01 21:32:56 +000010390 Var->setReferenced(true);
Douglas Gregorf02455e2012-02-10 09:26:04 +000010391 Var->setUsed(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010392
10393 // When the field has array type, create index variables for each
10394 // dimension of the array. We use these index variables to subscript
10395 // the source array, and other clients (e.g., CodeGen) will perform
10396 // the necessary iteration with these index variables.
10397 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor199cec72012-02-09 02:45:47 +000010398 QualType BaseType = FieldType;
10399 QualType SizeType = S.Context.getSizeType();
Douglas Gregor54fcea62012-02-13 16:35:30 +000010400 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor199cec72012-02-09 02:45:47 +000010401 while (const ConstantArrayType *Array
10402 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor199cec72012-02-09 02:45:47 +000010403 // Create the iteration variable for this array index.
10404 IdentifierInfo *IterationVarName = 0;
10405 {
10406 SmallString<8> Str;
10407 llvm::raw_svector_ostream OS(Str);
10408 OS << "__i" << IndexVariables.size();
10409 IterationVarName = &S.Context.Idents.get(OS.str());
10410 }
10411 VarDecl *IterationVar
10412 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10413 IterationVarName, SizeType,
10414 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10415 SC_None, SC_None);
10416 IndexVariables.push_back(IterationVar);
Douglas Gregor54fcea62012-02-13 16:35:30 +000010417 LSI->ArrayIndexVars.push_back(IterationVar);
10418
Douglas Gregor199cec72012-02-09 02:45:47 +000010419 // Create a reference to the iteration variable.
10420 ExprResult IterationVarRef
10421 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10422 assert(!IterationVarRef.isInvalid() &&
10423 "Reference to invented variable cannot fail!");
10424 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10425 assert(!IterationVarRef.isInvalid() &&
10426 "Conversion of invented variable cannot fail!");
10427
10428 // Subscript the array with this iteration variable.
10429 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10430 Ref, Loc, IterationVarRef.take(), Loc);
10431 if (Subscript.isInvalid()) {
10432 S.CleanupVarDeclMarking();
10433 S.DiscardCleanupsInEvaluationContext();
10434 S.PopExpressionEvaluationContext();
10435 return ExprError();
10436 }
10437
10438 Ref = Subscript.take();
10439 BaseType = Array->getElementType();
10440 }
10441
10442 // Construct the entity that we will be initializing. For an array, this
10443 // will be first element in the array, which may require several levels
10444 // of array-subscript entities.
10445 SmallVector<InitializedEntity, 4> Entities;
10446 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor19666fb2012-02-15 16:57:26 +000010447 Entities.push_back(
10448 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor199cec72012-02-09 02:45:47 +000010449 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10450 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10451 0,
10452 Entities.back()));
10453
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010454 InitializationKind InitKind
10455 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor199cec72012-02-09 02:45:47 +000010456 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010457 ExprResult Result(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010458 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010459 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010460
10461 // If this initialization requires any cleanups (e.g., due to a
10462 // default argument to a copy constructor), note that for the
10463 // lambda.
10464 if (S.ExprNeedsCleanups)
10465 LSI->ExprNeedsCleanups = true;
10466
10467 // Exit the expression evaluation context used for the capture.
10468 S.CleanupVarDeclMarking();
10469 S.DiscardCleanupsInEvaluationContext();
10470 S.PopExpressionEvaluationContext();
10471 return Result;
Douglas Gregor199cec72012-02-09 02:45:47 +000010472}
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010473
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010474bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10475 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10476 bool BuildAndDiagnose,
10477 QualType &CaptureType,
10478 QualType &DeclRefType) {
10479 bool Nested = false;
Douglas Gregor81495f32012-02-12 18:42:33 +000010480
Eli Friedman24af8502012-02-03 22:47:37 +000010481 DeclContext *DC = CurContext;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010482 if (Var->getDeclContext() == DC) return true;
10483 if (!Var->hasLocalStorage()) return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010484
Douglas Gregor81495f32012-02-12 18:42:33 +000010485 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010486
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010487 // Walk up the stack to determine whether we can capture the variable,
10488 // performing the "simple" checks that don't depend on type. We stop when
10489 // we've either hit the declared scope of the variable or find an existing
10490 // capture of that variable.
10491 CaptureType = Var->getType();
10492 DeclRefType = CaptureType.getNonReferenceType();
10493 bool Explicit = (Kind != TryCapture_Implicit);
10494 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010495 do {
Eli Friedman24af8502012-02-03 22:47:37 +000010496 // Only block literals and lambda expressions can capture; other
Eli Friedman9bb33f52012-02-03 02:04:35 +000010497 // scopes don't work.
Eli Friedman24af8502012-02-03 22:47:37 +000010498 DeclContext *ParentDC;
10499 if (isa<BlockDecl>(DC))
10500 ParentDC = DC->getParent();
10501 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregor81495f32012-02-12 18:42:33 +000010502 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedman24af8502012-02-03 22:47:37 +000010503 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10504 ParentDC = DC->getParent()->getParent();
Douglas Gregor81495f32012-02-12 18:42:33 +000010505 else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010506 if (BuildAndDiagnose)
Douglas Gregor81495f32012-02-12 18:42:33 +000010507 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010508 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010509 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010510
Eli Friedman24af8502012-02-03 22:47:37 +000010511 CapturingScopeInfo *CSI =
Douglas Gregor81495f32012-02-12 18:42:33 +000010512 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010513
Eli Friedman24af8502012-02-03 22:47:37 +000010514 // Check whether we've already captured it.
Douglas Gregor81495f32012-02-12 18:42:33 +000010515 if (CSI->CaptureMap.count(Var)) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010516 // If we found a capture, any subcaptures are nested.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010517 Nested = true;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010518
10519 // Retrieve the capture type for this variable.
10520 CaptureType = CSI->getCapture(Var).getCaptureType();
10521
10522 // Compute the type of an expression that refers to this variable.
10523 DeclRefType = CaptureType.getNonReferenceType();
10524
10525 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10526 if (Cap.isCopyCapture() &&
10527 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10528 DeclRefType.addConst();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010529 break;
10530 }
10531
Douglas Gregor81495f32012-02-12 18:42:33 +000010532 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010533 bool IsLambda = !IsBlock;
Eli Friedman24af8502012-02-03 22:47:37 +000010534
10535 // Lambdas are not allowed to capture unnamed variables
10536 // (e.g. anonymous unions).
10537 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10538 // assuming that's the intent.
Douglas Gregor81495f32012-02-12 18:42:33 +000010539 if (IsLambda && !Var->getDeclName()) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010540 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010541 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10542 Diag(Var->getLocation(), diag::note_declared_at);
10543 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010544 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010545 }
10546
10547 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010548 if (Var->getType()->isVariablyModifiedType()) {
10549 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010550 if (IsBlock)
10551 Diag(Loc, diag::err_ref_vm_type);
10552 else
10553 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10554 Diag(Var->getLocation(), diag::note_previous_decl)
10555 << Var->getDeclName();
10556 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010557 return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010558 }
10559
Eli Friedman24af8502012-02-03 22:47:37 +000010560 // Lambdas are not allowed to capture __block variables; they don't
10561 // support the expected semantics.
Douglas Gregor81495f32012-02-12 18:42:33 +000010562 if (IsLambda && HasBlocksAttr) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010563 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010564 Diag(Loc, diag::err_lambda_capture_block)
10565 << Var->getDeclName();
10566 Diag(Var->getLocation(), diag::note_previous_decl)
10567 << Var->getDeclName();
10568 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010569 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010570 }
10571
Douglas Gregor81495f32012-02-12 18:42:33 +000010572 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10573 // No capture-default
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010574 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010575 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10576 Diag(Var->getLocation(), diag::note_previous_decl)
10577 << Var->getDeclName();
10578 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10579 diag::note_lambda_decl);
10580 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010581 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010582 }
10583
10584 FunctionScopesIndex--;
10585 DC = ParentDC;
10586 Explicit = false;
10587 } while (!Var->getDeclContext()->Equals(DC));
10588
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010589 // Walk back down the scope stack, computing the type of the capture at
10590 // each step, checking type-specific requirements, and adding captures if
10591 // requested.
10592 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10593 ++I) {
10594 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor812d8f62012-02-18 05:51:20 +000010595
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010596 // Compute the type of the capture and of a reference to the capture within
10597 // this scope.
10598 if (isa<BlockScopeInfo>(CSI)) {
10599 Expr *CopyExpr = 0;
10600 bool ByRef = false;
10601
10602 // Blocks are not allowed to capture arrays.
10603 if (CaptureType->isArrayType()) {
10604 if (BuildAndDiagnose) {
10605 Diag(Loc, diag::err_ref_array_type);
10606 Diag(Var->getLocation(), diag::note_previous_decl)
10607 << Var->getDeclName();
10608 }
10609 return true;
10610 }
10611
John McCall67cd5e02012-03-30 05:23:48 +000010612 // Forbid the block-capture of autoreleasing variables.
10613 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10614 if (BuildAndDiagnose) {
10615 Diag(Loc, diag::err_arc_autoreleasing_capture)
10616 << /*block*/ 0;
10617 Diag(Var->getLocation(), diag::note_previous_decl)
10618 << Var->getDeclName();
10619 }
10620 return true;
10621 }
10622
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010623 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10624 // Block capture by reference does not change the capture or
10625 // declaration reference types.
10626 ByRef = true;
10627 } else {
10628 // Block capture by copy introduces 'const'.
10629 CaptureType = CaptureType.getNonReferenceType().withConst();
10630 DeclRefType = CaptureType;
10631
David Blaikiebbafb8a2012-03-11 07:00:24 +000010632 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010633 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10634 // The capture logic needs the destructor, so make sure we mark it.
10635 // Usually this is unnecessary because most local variables have
10636 // their destructors marked at declaration time, but parameters are
10637 // an exception because it's technically only the call site that
10638 // actually requires the destructor.
10639 if (isa<ParmVarDecl>(Var))
10640 FinalizeVarWithDestructor(Var, Record);
10641
10642 // According to the blocks spec, the capture of a variable from
10643 // the stack requires a const copy constructor. This is not true
10644 // of the copy/move done to move a __block variable to the heap.
John McCall113bee02012-03-10 09:33:50 +000010645 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010646 DeclRefType.withConst(),
10647 VK_LValue, Loc);
10648 ExprResult Result
10649 = PerformCopyInitialization(
10650 InitializedEntity::InitializeBlock(Var->getLocation(),
10651 CaptureType, false),
10652 Loc, Owned(DeclRef));
10653
10654 // Build a full-expression copy expression if initialization
10655 // succeeded and used a non-trivial constructor. Recover from
10656 // errors by pretending that the copy isn't necessary.
10657 if (!Result.isInvalid() &&
10658 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10659 ->isTrivial()) {
10660 Result = MaybeCreateExprWithCleanups(Result);
10661 CopyExpr = Result.take();
10662 }
10663 }
10664 }
10665 }
10666
10667 // Actually capture the variable.
10668 if (BuildAndDiagnose)
10669 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10670 SourceLocation(), CaptureType, CopyExpr);
10671 Nested = true;
10672 continue;
10673 }
Douglas Gregor812d8f62012-02-18 05:51:20 +000010674
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010675 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10676
10677 // Determine whether we are capturing by reference or by value.
10678 bool ByRef = false;
10679 if (I == N - 1 && Kind != TryCapture_Implicit) {
10680 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedman24af8502012-02-03 22:47:37 +000010681 } else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010682 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedman24af8502012-02-03 22:47:37 +000010683 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010684
10685 // Compute the type of the field that will capture this variable.
10686 if (ByRef) {
10687 // C++11 [expr.prim.lambda]p15:
10688 // An entity is captured by reference if it is implicitly or
10689 // explicitly captured but not captured by copy. It is
10690 // unspecified whether additional unnamed non-static data
10691 // members are declared in the closure type for entities
10692 // captured by reference.
10693 //
10694 // FIXME: It is not clear whether we want to build an lvalue reference
10695 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10696 // to do the former, while EDG does the latter. Core issue 1249 will
10697 // clarify, but for now we follow GCC because it's a more permissive and
10698 // easily defensible position.
10699 CaptureType = Context.getLValueReferenceType(DeclRefType);
10700 } else {
10701 // C++11 [expr.prim.lambda]p14:
10702 // For each entity captured by copy, an unnamed non-static
10703 // data member is declared in the closure type. The
10704 // declaration order of these members is unspecified. The type
10705 // of such a data member is the type of the corresponding
10706 // captured entity if the entity is not a reference to an
10707 // object, or the referenced type otherwise. [Note: If the
10708 // captured entity is a reference to a function, the
10709 // corresponding data member is also a reference to a
10710 // function. - end note ]
10711 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10712 if (!RefType->getPointeeType()->isFunctionType())
10713 CaptureType = RefType->getPointeeType();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010714 }
John McCall67cd5e02012-03-30 05:23:48 +000010715
10716 // Forbid the lambda copy-capture of autoreleasing variables.
10717 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10718 if (BuildAndDiagnose) {
10719 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10720 Diag(Var->getLocation(), diag::note_previous_decl)
10721 << Var->getDeclName();
10722 }
10723 return true;
10724 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010725 }
10726
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010727 // Capture this variable in the lambda.
10728 Expr *CopyExpr = 0;
10729 if (BuildAndDiagnose) {
10730 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregora8182f92012-05-16 17:01:33 +000010731 DeclRefType, Loc,
10732 I == N-1);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010733 if (!Result.isInvalid())
10734 CopyExpr = Result.take();
10735 }
10736
10737 // Compute the type of a reference to this captured variable.
10738 if (ByRef)
10739 DeclRefType = CaptureType.getNonReferenceType();
10740 else {
10741 // C++ [expr.prim.lambda]p5:
10742 // The closure type for a lambda-expression has a public inline
10743 // function call operator [...]. This function call operator is
10744 // declared const (9.3.1) if and only if the lambda-expression’s
10745 // parameter-declaration-clause is not followed by mutable.
10746 DeclRefType = CaptureType.getNonReferenceType();
10747 if (!LSI->Mutable && !CaptureType->isReferenceType())
10748 DeclRefType.addConst();
10749 }
10750
10751 // Add the capture.
10752 if (BuildAndDiagnose)
10753 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10754 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010755 Nested = true;
10756 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010757
10758 return false;
10759}
10760
10761bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10762 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10763 QualType CaptureType;
10764 QualType DeclRefType;
10765 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10766 /*BuildAndDiagnose=*/true, CaptureType,
10767 DeclRefType);
10768}
10769
10770QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10771 QualType CaptureType;
10772 QualType DeclRefType;
10773
10774 // Determine whether we can capture this variable.
10775 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10776 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10777 return QualType();
10778
10779 return DeclRefType;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010780}
10781
Eli Friedman3bda6b12012-02-02 23:15:15 +000010782static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10783 SourceLocation Loc) {
10784 // Keep track of used but undefined variables.
Eli Friedman130bbd02012-02-04 00:54:05 +000010785 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar9d355812012-03-09 01:51:51 +000010786 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman130bbd02012-02-04 00:54:05 +000010787 Var->getLinkage() != ExternalLinkage &&
10788 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010789 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10790 if (old.isInvalid()) old = Loc;
10791 }
10792
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010793 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010794
Eli Friedman3bda6b12012-02-02 23:15:15 +000010795 Var->setUsed(true);
10796}
10797
10798void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10799 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10800 // an object that satisfies the requirements for appearing in a
10801 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10802 // is immediately applied." This function handles the lvalue-to-rvalue
10803 // conversion part.
10804 MaybeODRUseExprs.erase(E->IgnoreParens());
10805}
10806
Eli Friedmanc6237c62012-02-29 03:16:56 +000010807ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10808 if (!Res.isUsable())
10809 return Res;
10810
10811 // If a constant-expression is a reference to a variable where we delay
10812 // deciding whether it is an odr-use, just assume we will apply the
10813 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10814 // (a non-type template argument), we have special handling anyway.
10815 UpdateMarkingForLValueToRValue(Res.get());
10816 return Res;
10817}
10818
Eli Friedman3bda6b12012-02-02 23:15:15 +000010819void Sema::CleanupVarDeclMarking() {
10820 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10821 e = MaybeODRUseExprs.end();
10822 i != e; ++i) {
10823 VarDecl *Var;
10824 SourceLocation Loc;
John McCall113bee02012-03-10 09:33:50 +000010825 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010826 Var = cast<VarDecl>(DRE->getDecl());
10827 Loc = DRE->getLocation();
10828 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10829 Var = cast<VarDecl>(ME->getMemberDecl());
10830 Loc = ME->getMemberLoc();
10831 } else {
10832 llvm_unreachable("Unexpcted expression");
10833 }
10834
10835 MarkVarDeclODRUsed(*this, Var, Loc);
10836 }
10837
10838 MaybeODRUseExprs.clear();
10839}
10840
10841// Mark a VarDecl referenced, and perform the necessary handling to compute
10842// odr-uses.
10843static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10844 VarDecl *Var, Expr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010845 Var->setReferenced();
10846
Eli Friedman3bda6b12012-02-02 23:15:15 +000010847 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010848 return;
10849
10850 // Implicit instantiation of static data members of class templates.
Richard Smithd3cf2382012-02-15 02:42:50 +000010851 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010852 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10853 assert(MSInfo && "Missing member specialization information?");
Richard Smithd3cf2382012-02-15 02:42:50 +000010854 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10855 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010856 (!AlreadyInstantiated ||
10857 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smithd3cf2382012-02-15 02:42:50 +000010858 if (!AlreadyInstantiated) {
10859 // This is a modification of an existing AST node. Notify listeners.
10860 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10861 L->StaticDataMemberInstantiated(Var);
10862 MSInfo->setPointOfInstantiation(Loc);
10863 }
10864 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar9d355812012-03-09 01:51:51 +000010865 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010866 // Do not defer instantiations of variables which could be used in a
10867 // constant expression.
Richard Smithd3cf2382012-02-15 02:42:50 +000010868 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010869 else
Richard Smithd3cf2382012-02-15 02:42:50 +000010870 SemaRef.PendingInstantiations.push_back(
10871 std::make_pair(Var, PointOfInstantiation));
Eli Friedmanfa0df832012-02-02 03:46:19 +000010872 }
10873 }
10874
Eli Friedman3bda6b12012-02-02 23:15:15 +000010875 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10876 // an object that satisfies the requirements for appearing in a
10877 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10878 // is immediately applied." We check the first part here, and
10879 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10880 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith35ecb362012-03-02 04:14:40 +000010881 // C++03 depends on whether we get the C++03 version correct. This does not
10882 // apply to references, since they are not objects.
Eli Friedman3bda6b12012-02-02 23:15:15 +000010883 const VarDecl *DefVD;
Richard Smith35ecb362012-03-02 04:14:40 +000010884 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010885 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedman3bda6b12012-02-02 23:15:15 +000010886 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10887 SemaRef.MaybeODRUseExprs.insert(E);
10888 else
10889 MarkVarDeclODRUsed(SemaRef, Var, Loc);
10890}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010891
Eli Friedman3bda6b12012-02-02 23:15:15 +000010892/// \brief Mark a variable referenced, and check whether it is odr-used
10893/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
10894/// used directly for normal expressions referring to VarDecl.
10895void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10896 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010897}
10898
10899static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10900 Decl *D, Expr *E) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010901 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10902 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10903 return;
10904 }
10905
Eli Friedmanfa0df832012-02-02 03:46:19 +000010906 SemaRef.MarkAnyDeclReferenced(Loc, D);
Rafael Espindola49e860b2012-06-26 17:45:31 +000010907
10908 // If this is a call to a method via a cast, also mark the method in the
10909 // derived class used in case codegen can devirtualize the call.
10910 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10911 if (!ME)
10912 return;
10913 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
10914 if (!MD)
10915 return;
10916 const Expr *Base = ME->getBase();
Rafael Espindolab7f5a9c2012-06-27 18:18:05 +000010917 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000010918 if (!MostDerivedClassDecl)
10919 return;
10920 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Rafael Espindolaa245edc2012-06-27 17:44:39 +000010921 if (!DM)
10922 return;
Rafael Espindola49e860b2012-06-26 17:45:31 +000010923 SemaRef.MarkAnyDeclReferenced(Loc, DM);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010924}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010925
Eli Friedmanfa0df832012-02-02 03:46:19 +000010926/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10927void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10928 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10929}
10930
10931/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10932void Sema::MarkMemberReferenced(MemberExpr *E) {
10933 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10934}
10935
Douglas Gregorf02455e2012-02-10 09:26:04 +000010936/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedmanfa0df832012-02-02 03:46:19 +000010937/// marks the declaration referenced, and performs odr-use checking for functions
10938/// and variables. This method should not be used when building an normal
10939/// expression which refers to a variable.
10940void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10941 if (VarDecl *VD = dyn_cast<VarDecl>(D))
10942 MarkVariableReferenced(Loc, VD);
10943 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10944 MarkFunctionReferenced(Loc, FD);
10945 else
10946 D->setReferenced();
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010947}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010948
Douglas Gregor5597ab42010-05-07 23:12:07 +000010949namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000010950 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000010951 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000010952 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000010953 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10954 Sema &S;
10955 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010956
Douglas Gregor5597ab42010-05-07 23:12:07 +000010957 public:
10958 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010959
Douglas Gregor5597ab42010-05-07 23:12:07 +000010960 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010961
10962 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10963 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010964 };
10965}
10966
Chandler Carruthaf80f662010-06-09 08:17:30 +000010967bool MarkReferencedDecls::TraverseTemplateArgument(
10968 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010969 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +000010970 if (Decl *D = Arg.getAsDecl())
10971 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010972 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010973
10974 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010975}
10976
Chandler Carruthaf80f662010-06-09 08:17:30 +000010977bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010978 if (ClassTemplateSpecializationDecl *Spec
10979 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10980 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000010981 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000010982 }
10983
Chandler Carruthc65667c2010-06-10 10:31:57 +000010984 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000010985}
10986
10987void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10988 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000010989 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000010990}
10991
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010992namespace {
10993 /// \brief Helper class that marks all of the declarations referenced by
10994 /// potentially-evaluated subexpressions as "referenced".
10995 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10996 Sema &S;
Douglas Gregor680e9e02012-02-21 19:11:17 +000010997 bool SkipLocalVariables;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010998
10999 public:
11000 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11001
Douglas Gregor680e9e02012-02-21 19:11:17 +000011002 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11003 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011004
11005 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000011006 // If we were asked not to visit local variables, don't.
11007 if (SkipLocalVariables) {
11008 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11009 if (VD->hasLocalStorage())
11010 return;
11011 }
11012
Eli Friedmanfa0df832012-02-02 03:46:19 +000011013 S.MarkDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011014 }
11015
11016 void VisitMemberExpr(MemberExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011017 S.MarkMemberReferenced(E);
Douglas Gregor32b3de52010-09-11 23:32:50 +000011018 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011019 }
11020
John McCall28fc7092011-11-10 05:35:25 +000011021 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011022 S.MarkFunctionReferenced(E->getLocStart(),
John McCall28fc7092011-11-10 05:35:25 +000011023 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11024 Visit(E->getSubExpr());
11025 }
11026
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011027 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011028 if (E->getOperatorNew())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011029 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011030 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011031 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000011032 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011033 }
Sebastian Redl6047f072012-02-16 12:22:20 +000011034
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011035 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11036 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011037 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000011038 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11039 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11040 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedmanfa0df832012-02-02 03:46:19 +000011041 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000011042 S.LookupDestructor(Record));
11043 }
11044
Douglas Gregor32b3de52010-09-11 23:32:50 +000011045 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011046 }
11047
11048 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011049 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000011050 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011051 }
11052
Douglas Gregorf0873f42010-10-19 17:17:35 +000011053 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11054 Visit(E->getExpr());
11055 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000011056
11057 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11058 Inherited::VisitImplicitCastExpr(E);
11059
11060 if (E->getCastKind() == CK_LValueToRValue)
11061 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11062 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011063 };
11064}
11065
11066/// \brief Mark any declarations that appear within this expression or any
11067/// potentially-evaluated subexpressions as "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +000011068///
11069/// \param SkipLocalVariables If true, don't mark local variables as
11070/// 'referenced'.
11071void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11072 bool SkipLocalVariables) {
11073 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011074}
11075
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011076/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11077/// of the program being compiled.
11078///
11079/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011080/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011081/// possibility that the code will actually be executable. Code in sizeof()
11082/// expressions, code used only during overload resolution, etc., are not
11083/// potentially evaluated. This routine will suppress such diagnostics or,
11084/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011085/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011086/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011087///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011088/// This routine should be used for all diagnostics that describe the run-time
11089/// behavior of a program, such as passing a non-POD value through an ellipsis.
11090/// Failure to do so will likely result in spurious diagnostics or failures
11091/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +000011092bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011093 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +000011094 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011095 case Unevaluated:
11096 // The argument will never be evaluated, so don't complain.
11097 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011098
Richard Smith764d2fe2011-12-20 02:08:33 +000011099 case ConstantEvaluated:
11100 // Relevant diagnostics should be produced by constant evaluation.
11101 break;
11102
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011103 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011104 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +000011105 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +000011106 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +000011107 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +000011108 }
11109 else
11110 Diag(Loc, PD);
11111
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011112 return true;
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011113 }
11114
11115 return false;
11116}
11117
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011118bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11119 CallExpr *CE, FunctionDecl *FD) {
11120 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11121 return false;
11122
Richard Smithfd555f62012-02-22 02:04:18 +000011123 // If we're inside a decltype's expression, don't check for a valid return
11124 // type or construct temporaries until we know whether this is the last call.
11125 if (ExprEvalContexts.back().IsDecltype) {
11126 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11127 return false;
11128 }
11129
Douglas Gregora6c5abb2012-05-04 16:48:41 +000011130 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011131 FunctionDecl *FD;
11132 CallExpr *CE;
11133
11134 public:
11135 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11136 : FD(FD), CE(CE) { }
11137
11138 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11139 if (!FD) {
11140 S.Diag(Loc, diag::err_call_incomplete_return)
11141 << T << CE->getSourceRange();
11142 return;
11143 }
11144
11145 S.Diag(Loc, diag::err_call_function_incomplete_return)
11146 << CE->getSourceRange() << FD->getDeclName() << T;
11147 S.Diag(FD->getLocation(),
11148 diag::note_function_with_incomplete_return_type_declared_here)
11149 << FD->getDeclName();
11150 }
11151 } Diagnoser(FD, CE);
11152
11153 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011154 return true;
11155
11156 return false;
11157}
11158
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011159// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000011160// will prevent this condition from triggering, which is what we want.
11161void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11162 SourceLocation Loc;
11163
John McCall0506e4a2009-11-11 02:41:58 +000011164 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011165 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000011166
Chandler Carruthf87d6c02011-08-16 22:30:10 +000011167 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011168 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000011169 return;
11170
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011171 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11172
John McCallb0e419e2009-11-12 00:06:05 +000011173 // Greylist some idioms by putting them into a warning subcategory.
11174 if (ObjCMessageExpr *ME
11175 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11176 Selector Sel = ME->getSelector();
11177
John McCallb0e419e2009-11-12 00:06:05 +000011178 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +000011179 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000011180 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11181
11182 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000011183 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000011184 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11185 }
John McCall0506e4a2009-11-11 02:41:58 +000011186
John McCalld5707ab2009-10-12 21:59:07 +000011187 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +000011188 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011189 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000011190 return;
11191
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011192 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000011193 Loc = Op->getOperatorLoc();
Fariborz Jahanianf07bcc52012-08-29 17:17:11 +000011194 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11195 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11196 else {
John McCalld5707ab2009-10-12 21:59:07 +000011197 // Not an assignment.
11198 return;
11199 }
11200
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000011201 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011202
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011203 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000011204 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11205 Diag(Loc, diag::note_condition_assign_silence)
11206 << FixItHint::CreateInsertion(Open, "(")
11207 << FixItHint::CreateInsertion(Close, ")");
11208
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011209 if (IsOrAssign)
11210 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11211 << FixItHint::CreateReplacement(Loc, "!=");
11212 else
11213 Diag(Loc, diag::note_condition_assign_to_comparison)
11214 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000011215}
11216
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011217/// \brief Redundant parentheses over an equality comparison can indicate
11218/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +000011219void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011220 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +000011221 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011222 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11223 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000011224 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +000011225 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000011226 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011227
Richard Trieuba63ce62011-09-09 01:45:06 +000011228 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011229
11230 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000011231 if (opE->getOpcode() == BO_EQ &&
11232 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11233 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011234 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000011235
Ted Kremenekae022092011-02-02 02:20:30 +000011236 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011237 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000011238 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011239 << FixItHint::CreateRemoval(ParenERange.getBegin())
11240 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000011241 Diag(Loc, diag::note_equality_comparison_to_assign)
11242 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011243 }
11244}
11245
John Wiegley01296292011-04-08 18:41:53 +000011246ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000011247 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011248 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11249 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000011250
John McCall0009fcc2011-04-26 20:42:42 +000011251 ExprResult result = CheckPlaceholderExpr(E);
11252 if (result.isInvalid()) return ExprError();
11253 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000011254
John McCall0009fcc2011-04-26 20:42:42 +000011255 if (!E->isTypeDependent()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011256 if (getLangOpts().CPlusPlus)
John McCall34376a62010-12-04 03:47:34 +000011257 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11258
John Wiegley01296292011-04-08 18:41:53 +000011259 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11260 if (ERes.isInvalid())
11261 return ExprError();
11262 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000011263
11264 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000011265 if (!T->isScalarType()) { // C99 6.8.4.1p1
11266 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11267 << T << E->getSourceRange();
11268 return ExprError();
11269 }
John McCalld5707ab2009-10-12 21:59:07 +000011270 }
11271
John Wiegley01296292011-04-08 18:41:53 +000011272 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000011273}
Douglas Gregore60e41a2010-05-06 17:25:47 +000011274
John McCalldadc5752010-08-24 06:29:42 +000011275ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +000011276 Expr *SubExpr) {
11277 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +000011278 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011279
Richard Trieuba63ce62011-09-09 01:45:06 +000011280 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000011281}
John McCall36e7fe32010-10-12 00:20:44 +000011282
John McCall31996342011-04-07 08:22:57 +000011283namespace {
John McCall2979fe02011-04-12 00:42:48 +000011284 /// A visitor for rebuilding a call to an __unknown_any expression
11285 /// to have an appropriate type.
11286 struct RebuildUnknownAnyFunction
11287 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11288
11289 Sema &S;
11290
11291 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11292
11293 ExprResult VisitStmt(Stmt *S) {
11294 llvm_unreachable("unexpected statement!");
John McCall2979fe02011-04-12 00:42:48 +000011295 }
11296
Richard Trieu10162ab2011-09-09 03:59:41 +000011297 ExprResult VisitExpr(Expr *E) {
11298 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11299 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011300 return ExprError();
11301 }
11302
11303 /// Rebuild an expression which simply semantically wraps another
11304 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000011305 template <class T> ExprResult rebuildSugarExpr(T *E) {
11306 ExprResult SubResult = Visit(E->getSubExpr());
11307 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000011308
Richard Trieu10162ab2011-09-09 03:59:41 +000011309 Expr *SubExpr = SubResult.take();
11310 E->setSubExpr(SubExpr);
11311 E->setType(SubExpr->getType());
11312 E->setValueKind(SubExpr->getValueKind());
11313 assert(E->getObjectKind() == OK_Ordinary);
11314 return E;
John McCall2979fe02011-04-12 00:42:48 +000011315 }
11316
Richard Trieu10162ab2011-09-09 03:59:41 +000011317 ExprResult VisitParenExpr(ParenExpr *E) {
11318 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011319 }
11320
Richard Trieu10162ab2011-09-09 03:59:41 +000011321 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11322 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011323 }
11324
Richard Trieu10162ab2011-09-09 03:59:41 +000011325 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11326 ExprResult SubResult = Visit(E->getSubExpr());
11327 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000011328
Richard Trieu10162ab2011-09-09 03:59:41 +000011329 Expr *SubExpr = SubResult.take();
11330 E->setSubExpr(SubExpr);
11331 E->setType(S.Context.getPointerType(SubExpr->getType()));
11332 assert(E->getValueKind() == VK_RValue);
11333 assert(E->getObjectKind() == OK_Ordinary);
11334 return E;
John McCall2979fe02011-04-12 00:42:48 +000011335 }
11336
Richard Trieu10162ab2011-09-09 03:59:41 +000011337 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11338 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011339
Richard Trieu10162ab2011-09-09 03:59:41 +000011340 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +000011341
Richard Trieu10162ab2011-09-09 03:59:41 +000011342 assert(E->getValueKind() == VK_RValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011343 if (S.getLangOpts().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +000011344 !(isa<CXXMethodDecl>(VD) &&
11345 cast<CXXMethodDecl>(VD)->isInstance()))
11346 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +000011347
Richard Trieu10162ab2011-09-09 03:59:41 +000011348 return E;
John McCall2979fe02011-04-12 00:42:48 +000011349 }
11350
Richard Trieu10162ab2011-09-09 03:59:41 +000011351 ExprResult VisitMemberExpr(MemberExpr *E) {
11352 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011353 }
11354
Richard Trieu10162ab2011-09-09 03:59:41 +000011355 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11356 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +000011357 }
11358 };
11359}
11360
11361/// Given a function expression of unknown-any type, try to rebuild it
11362/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011363static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11364 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11365 if (Result.isInvalid()) return ExprError();
11366 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +000011367}
11368
11369namespace {
John McCall2d2e8702011-04-11 07:02:50 +000011370 /// A visitor for rebuilding an expression of type __unknown_anytype
11371 /// into one which resolves the type directly on the referring
11372 /// expression. Strict preservation of the original source
11373 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000011374 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000011375 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000011376
11377 Sema &S;
11378
11379 /// The current destination type.
11380 QualType DestType;
11381
Richard Trieu10162ab2011-09-09 03:59:41 +000011382 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11383 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +000011384
John McCall39439732011-04-09 22:50:59 +000011385 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000011386 llvm_unreachable("unexpected statement!");
John McCall31996342011-04-07 08:22:57 +000011387 }
11388
Richard Trieu10162ab2011-09-09 03:59:41 +000011389 ExprResult VisitExpr(Expr *E) {
11390 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11391 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011392 return ExprError();
John McCall31996342011-04-07 08:22:57 +000011393 }
11394
Richard Trieu10162ab2011-09-09 03:59:41 +000011395 ExprResult VisitCallExpr(CallExpr *E);
11396 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +000011397
John McCall39439732011-04-09 22:50:59 +000011398 /// Rebuild an expression which simply semantically wraps another
11399 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000011400 template <class T> ExprResult rebuildSugarExpr(T *E) {
11401 ExprResult SubResult = Visit(E->getSubExpr());
11402 if (SubResult.isInvalid()) return ExprError();
11403 Expr *SubExpr = SubResult.take();
11404 E->setSubExpr(SubExpr);
11405 E->setType(SubExpr->getType());
11406 E->setValueKind(SubExpr->getValueKind());
11407 assert(E->getObjectKind() == OK_Ordinary);
11408 return E;
John McCall39439732011-04-09 22:50:59 +000011409 }
John McCall31996342011-04-07 08:22:57 +000011410
Richard Trieu10162ab2011-09-09 03:59:41 +000011411 ExprResult VisitParenExpr(ParenExpr *E) {
11412 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011413 }
11414
Richard Trieu10162ab2011-09-09 03:59:41 +000011415 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11416 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011417 }
11418
Richard Trieu10162ab2011-09-09 03:59:41 +000011419 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11420 const PointerType *Ptr = DestType->getAs<PointerType>();
11421 if (!Ptr) {
11422 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11423 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011424 return ExprError();
11425 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011426 assert(E->getValueKind() == VK_RValue);
11427 assert(E->getObjectKind() == OK_Ordinary);
11428 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000011429
11430 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011431 DestType = Ptr->getPointeeType();
11432 ExprResult SubResult = Visit(E->getSubExpr());
11433 if (SubResult.isInvalid()) return ExprError();
11434 E->setSubExpr(SubResult.take());
11435 return E;
John McCall2979fe02011-04-12 00:42:48 +000011436 }
11437
Richard Trieu10162ab2011-09-09 03:59:41 +000011438 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +000011439
Richard Trieu10162ab2011-09-09 03:59:41 +000011440 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +000011441
Richard Trieu10162ab2011-09-09 03:59:41 +000011442 ExprResult VisitMemberExpr(MemberExpr *E) {
11443 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011444 }
John McCall39439732011-04-09 22:50:59 +000011445
Richard Trieu10162ab2011-09-09 03:59:41 +000011446 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11447 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +000011448 }
11449 };
11450}
11451
John McCall2d2e8702011-04-11 07:02:50 +000011452/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +000011453ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11454 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011455
11456 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000011457 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000011458 FK_FunctionPointer,
11459 FK_BlockPointer
11460 };
11461
Richard Trieu10162ab2011-09-09 03:59:41 +000011462 FnKind Kind;
11463 QualType CalleeType = CalleeExpr->getType();
11464 if (CalleeType == S.Context.BoundMemberTy) {
11465 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11466 Kind = FK_MemberFunction;
11467 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11468 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11469 CalleeType = Ptr->getPointeeType();
11470 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011471 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011472 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11473 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011474 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011475 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +000011476
11477 // Verify that this is a legal result type of a function.
11478 if (DestType->isArrayType() || DestType->isFunctionType()) {
11479 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +000011480 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +000011481 diagID = diag::err_block_returning_array_function;
11482
Richard Trieu10162ab2011-09-09 03:59:41 +000011483 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +000011484 << DestType->isFunctionType() << DestType;
11485 return ExprError();
11486 }
11487
11488 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +000011489 E->setType(DestType.getNonLValueExprType(S.Context));
11490 E->setValueKind(Expr::getValueKindForType(DestType));
11491 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011492
11493 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +000011494 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +000011495 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011496 Proto->arg_type_begin(),
11497 Proto->getNumArgs(),
11498 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011499 else
11500 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011501 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011502
11503 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011504 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +000011505 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000011506 // Nothing to do.
11507 break;
11508
11509 case FK_FunctionPointer:
11510 DestType = S.Context.getPointerType(DestType);
11511 break;
11512
11513 case FK_BlockPointer:
11514 DestType = S.Context.getBlockPointerType(DestType);
11515 break;
11516 }
11517
11518 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +000011519 ExprResult CalleeResult = Visit(CalleeExpr);
11520 if (!CalleeResult.isUsable()) return ExprError();
11521 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +000011522
11523 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +000011524 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011525}
11526
Richard Trieu10162ab2011-09-09 03:59:41 +000011527ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011528 // Verify that this is a legal result type of a call.
11529 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +000011530 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +000011531 << DestType->isFunctionType() << DestType;
11532 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011533 }
11534
John McCall3f4138c2011-07-13 17:56:40 +000011535 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +000011536 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11537 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11538 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +000011539 }
John McCall2979fe02011-04-12 00:42:48 +000011540
John McCall2d2e8702011-04-11 07:02:50 +000011541 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +000011542 E->setType(DestType.getNonReferenceType());
11543 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000011544
Richard Trieu10162ab2011-09-09 03:59:41 +000011545 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011546}
11547
Richard Trieu10162ab2011-09-09 03:59:41 +000011548ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011549 // The only case we should ever see here is a function-to-pointer decay.
Sean Callanan2db103c2012-03-06 23:12:57 +000011550 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanan12495112012-03-06 21:34:12 +000011551 assert(E->getValueKind() == VK_RValue);
11552 assert(E->getObjectKind() == OK_Ordinary);
11553
11554 E->setType(DestType);
11555
11556 // Rebuild the sub-expression as the pointee (function) type.
11557 DestType = DestType->castAs<PointerType>()->getPointeeType();
11558
11559 ExprResult Result = Visit(E->getSubExpr());
11560 if (!Result.isUsable()) return ExprError();
11561
11562 E->setSubExpr(Result.take());
11563 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011564 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanan12495112012-03-06 21:34:12 +000011565 assert(E->getValueKind() == VK_RValue);
11566 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011567
Sean Callanan12495112012-03-06 21:34:12 +000011568 assert(isa<BlockPointerType>(E->getType()));
John McCall2979fe02011-04-12 00:42:48 +000011569
Sean Callanan12495112012-03-06 21:34:12 +000011570 E->setType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011571
Sean Callanan12495112012-03-06 21:34:12 +000011572 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11573 DestType = S.Context.getLValueReferenceType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011574
Sean Callanan12495112012-03-06 21:34:12 +000011575 ExprResult Result = Visit(E->getSubExpr());
11576 if (!Result.isUsable()) return ExprError();
11577
11578 E->setSubExpr(Result.take());
11579 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011580 } else {
Sean Callanan12495112012-03-06 21:34:12 +000011581 llvm_unreachable("Unhandled cast type!");
11582 }
John McCall2d2e8702011-04-11 07:02:50 +000011583}
11584
Richard Trieu10162ab2011-09-09 03:59:41 +000011585ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11586 ExprValueKind ValueKind = VK_LValue;
11587 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000011588
11589 // We know how to make this work for certain kinds of decls:
11590
11591 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000011592 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11593 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11594 DestType = Ptr->getPointeeType();
11595 ExprResult Result = resolveDecl(E, VD);
11596 if (Result.isInvalid()) return ExprError();
11597 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000011598 CK_FunctionToPointerDecay, VK_RValue);
11599 }
11600
Richard Trieu10162ab2011-09-09 03:59:41 +000011601 if (!Type->isFunctionType()) {
11602 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11603 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000011604 return ExprError();
11605 }
John McCall2d2e8702011-04-11 07:02:50 +000011606
Richard Trieu10162ab2011-09-09 03:59:41 +000011607 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11608 if (MD->isInstance()) {
11609 ValueKind = VK_RValue;
11610 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000011611 }
11612
John McCall2d2e8702011-04-11 07:02:50 +000011613 // Function references aren't l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011614 if (!S.getLangOpts().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000011615 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000011616
11617 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000011618 } else if (isa<VarDecl>(VD)) {
11619 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11620 Type = RefTy->getPointeeType();
11621 } else if (Type->isFunctionType()) {
11622 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11623 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011624 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011625 }
11626
11627 // - nothing else
11628 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011629 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11630 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011631 return ExprError();
11632 }
11633
Richard Trieu10162ab2011-09-09 03:59:41 +000011634 VD->setType(DestType);
11635 E->setType(Type);
11636 E->setValueKind(ValueKind);
11637 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000011638}
11639
John McCall31996342011-04-07 08:22:57 +000011640/// Check a cast of an unknown-any type. We intentionally only
11641/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000011642ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11643 Expr *CastExpr, CastKind &CastKind,
11644 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000011645 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000011646 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000011647 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000011648
Richard Trieuba63ce62011-09-09 01:45:06 +000011649 CastExpr = result.take();
11650 VK = CastExpr->getValueKind();
11651 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000011652
Richard Trieuba63ce62011-09-09 01:45:06 +000011653 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000011654}
11655
Douglas Gregord8fb1e32011-12-01 01:37:36 +000011656ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11657 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11658}
11659
Richard Trieuba63ce62011-09-09 01:45:06 +000011660static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11661 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000011662 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000011663 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000011664 E = E->IgnoreParenImpCasts();
11665 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11666 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011667 diagID = diag::err_uncasted_call_of_unknown_any;
11668 } else {
John McCall31996342011-04-07 08:22:57 +000011669 break;
John McCall2d2e8702011-04-11 07:02:50 +000011670 }
John McCall31996342011-04-07 08:22:57 +000011671 }
11672
John McCall2d2e8702011-04-11 07:02:50 +000011673 SourceLocation loc;
11674 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000011675 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011676 loc = ref->getLocation();
11677 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011678 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011679 loc = mem->getMemberLoc();
11680 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011681 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011682 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidisa6011e22011-10-03 06:36:51 +000011683 loc = msg->getSelectorStartLoc();
John McCall2d2e8702011-04-11 07:02:50 +000011684 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000011685 if (!d) {
11686 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11687 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11688 << orig->getSourceRange();
11689 return ExprError();
11690 }
John McCall2d2e8702011-04-11 07:02:50 +000011691 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000011692 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11693 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011694 return ExprError();
11695 }
11696
11697 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000011698
11699 // Never recoverable.
11700 return ExprError();
11701}
11702
John McCall36e7fe32010-10-12 00:20:44 +000011703/// Check for operands with placeholder types and complain if found.
11704/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000011705ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall4124c492011-10-17 18:40:02 +000011706 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11707 if (!placeholderType) return Owned(E);
11708
11709 switch (placeholderType->getKind()) {
John McCall36e7fe32010-10-12 00:20:44 +000011710
John McCall31996342011-04-07 08:22:57 +000011711 // Overloaded expressions.
John McCall4124c492011-10-17 18:40:02 +000011712 case BuiltinType::Overload: {
John McCall50a2c2c2011-10-11 23:14:30 +000011713 // Try to resolve a single function template specialization.
11714 // This is obligatory.
11715 ExprResult result = Owned(E);
11716 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11717 return result;
11718
11719 // If that failed, try to recover with a call.
11720 } else {
11721 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11722 /*complain*/ true);
11723 return result;
11724 }
11725 }
John McCall31996342011-04-07 08:22:57 +000011726
John McCall0009fcc2011-04-26 20:42:42 +000011727 // Bound member functions.
John McCall4124c492011-10-17 18:40:02 +000011728 case BuiltinType::BoundMember: {
John McCall50a2c2c2011-10-11 23:14:30 +000011729 ExprResult result = Owned(E);
11730 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11731 /*complain*/ true);
11732 return result;
John McCall4124c492011-10-17 18:40:02 +000011733 }
11734
11735 // ARC unbridged casts.
11736 case BuiltinType::ARCUnbridgedCast: {
11737 Expr *realCast = stripARCUnbridgedCast(E);
11738 diagnoseARCUnbridgedCast(realCast);
11739 return Owned(realCast);
11740 }
John McCall0009fcc2011-04-26 20:42:42 +000011741
John McCall31996342011-04-07 08:22:57 +000011742 // Expressions of unknown type.
John McCall4124c492011-10-17 18:40:02 +000011743 case BuiltinType::UnknownAny:
John McCall31996342011-04-07 08:22:57 +000011744 return diagnoseUnknownAnyExpr(*this, E);
11745
John McCall526ab472011-10-25 17:37:35 +000011746 // Pseudo-objects.
11747 case BuiltinType::PseudoObject:
11748 return checkPseudoObjectRValue(E);
11749
John McCalle314e272011-10-18 21:02:43 +000011750 // Everything else should be impossible.
11751#define BUILTIN_TYPE(Id, SingletonId) \
11752 case BuiltinType::Id:
11753#define PLACEHOLDER_TYPE(Id, SingletonId)
11754#include "clang/AST/BuiltinTypes.def"
John McCall4124c492011-10-17 18:40:02 +000011755 break;
11756 }
11757
11758 llvm_unreachable("invalid placeholder type!");
John McCall36e7fe32010-10-12 00:20:44 +000011759}
Richard Trieu2c850c02011-04-21 21:44:26 +000011760
Richard Trieuba63ce62011-09-09 01:45:06 +000011761bool Sema::CheckCaseExpression(Expr *E) {
11762 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000011763 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000011764 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11765 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000011766 return false;
11767}
Ted Kremeneke65b0862012-03-06 20:05:56 +000011768
11769/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11770ExprResult
11771Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11772 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11773 "Unknown Objective-C Boolean value!");
11774 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanian29898f42012-04-16 21:03:30 +000011775 Context.ObjCBuiltinBoolTy, OpLoc));
Ted Kremeneke65b0862012-03-06 20:05:56 +000011776}